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;
476pub(crate) const 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
864pub(crate) fn 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
1473pub(crate) fn 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
1853#[path = "tee_perp_submission.rs"]
1854mod submission;
1855use submission::tee_submission_is_ambiguous;
1856pub(crate) use submission::SignedTeeSubmission;
1857
1858#[path = "tee_perp_preview.rs"]
1859mod preview;
1860pub use preview::{perp_preview_batch_action, perp_preview_order};
1861
1862#[derive(Debug, Clone)]
1869pub struct TeePerpMarketOrderParams {
1870 pub account: AccountAddress,
1871 pub asset: u32,
1872 pub side: Side,
1873 pub size: Decimal,
1874 pub reference_price: Decimal,
1876 pub size_decimals: u32,
1878 pub slippage_bps: Option<u32>,
1880 pub reduce_only: bool,
1881 pub client_order_id: Option<u128>,
1882 pub nonce: Option<u64>,
1883}
1884
1885#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1887pub enum TeePerpTriggerExecution {
1888 Market {
1890 size_decimals: u32,
1891 slippage_bps: Option<u32>,
1893 },
1894 Limit { price: Decimal },
1896}
1897
1898#[derive(Debug, Clone)]
1900pub struct TeePerpTriggerOrderParams {
1901 pub account: AccountAddress,
1902 pub asset: u32,
1903 pub side: Side,
1904 pub size: Decimal,
1905 pub trigger_price: Decimal,
1906 pub tpsl: TeePerpTpsl,
1908 pub execution: TeePerpTriggerExecution,
1909 pub reduce_only: bool,
1910 pub client_order_id: Option<u128>,
1912 pub nonce: Option<u64>,
1913}
1914
1915#[derive(Debug, Clone)]
1917pub struct TeePerpBracketOrderParams {
1918 pub account: AccountAddress,
1919 pub entry: TeePerpBracketEntry,
1920 pub take_profit: Option<TeePerpExit>,
1921 pub stop_loss: Option<TeePerpExit>,
1922 pub nonce: Option<u64>,
1923}
1924
1925#[derive(Debug, Clone)]
1927pub struct TeePerpPositionTpslParams {
1928 pub account: AccountAddress,
1929 pub asset: u32,
1930 pub position_side: Side,
1932 pub size: Decimal,
1933 pub take_profit: Option<TeePerpExit>,
1934 pub stop_loss: Option<TeePerpExit>,
1935 pub nonce: Option<u64>,
1936}
1937
1938#[derive(Debug, Clone)]
1940pub struct TeePerpScaleOrderParams {
1941 pub account: AccountAddress,
1942 pub asset: u32,
1943 pub side: Side,
1944 pub legs: Vec<PerpScaleLeg>,
1946 pub tif: PerpTimeInForce,
1947 pub reduce_only: bool,
1948 pub nonce: Option<u64>,
1949}
1950
1951#[derive(Debug, Clone)]
1955pub struct TeePerpOrderBatchParams {
1956 pub account: AccountAddress,
1957 pub nonce: u64,
1958 pub batch: TeePerpOrderBatchAction,
1959}
1960
1961#[derive(Debug, Clone, Copy)]
1963pub struct TeePerpLeverageParams {
1964 pub account: AccountAddress,
1965 pub asset: u32,
1966 pub is_cross: bool,
1968 pub leverage: u32,
1970 pub nonce: Option<u64>,
1971}
1972
1973#[derive(Debug, Clone, Copy)]
1976pub struct TeePerpModifyParams {
1977 pub account: AccountAddress,
1978 pub replacement: TeePerpOrderReplacement,
1979 pub nonce: Option<u64>,
1980}
1981
1982#[derive(Debug, Clone)]
1985pub struct TeePerpBatchModifyParams {
1986 pub account: AccountAddress,
1987 pub replacements: Vec<TeePerpOrderReplacement>,
1989 pub max_children: Option<usize>,
1993 pub nonce: Option<u64>,
1994}
1995
1996#[derive(Debug, Clone, Copy)]
1998pub struct TeePerpTwapParams {
1999 pub account: AccountAddress,
2000 pub asset: u32,
2001 pub side: Side,
2002 pub size: Decimal,
2004 pub reduce_only: bool,
2005 pub minutes: u32,
2007 pub randomize: bool,
2009 pub nonce: Option<u64>,
2010}
2011
2012#[derive(Debug, Clone, Copy)]
2014pub struct TeePerpTwapCancelParams {
2015 pub account: AccountAddress,
2016 pub asset: u32,
2017 pub twap_id: u64,
2019 pub nonce: Option<u64>,
2020}
2021
2022#[derive(Debug, Clone)]
2024pub struct ApproveHypercallBuilderParams {
2025 pub rpc_url: String,
2027 pub account: AccountAddress,
2029 pub builder: Option<AccountAddress>,
2031}
2032
2033#[derive(Debug, Clone)]
2035pub struct TeeApiWalletApprovalChallenge {
2036 pub account: AccountAddress,
2037 pub manager: AccountAddress,
2038 pub timestamp: i64,
2040 pub authentication_signature: String,
2041 pub package: TeeApiWalletApprovalPackage,
2042}
2043
2044#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2046pub enum TeeApiWalletApprovalProgress {
2047 Pending,
2048 Finalized,
2049 Failed,
2050}
2051
2052pub fn tee_api_wallet_approval_progress(
2054 status: &DirectiveStatusResponse,
2055) -> TeeApiWalletApprovalProgress {
2056 if status.domain_status == DirectiveDomainStatus::Completed
2057 && status.delivery_status == DirectiveDeliveryStatus::Finalized
2058 {
2059 return TeeApiWalletApprovalProgress::Finalized;
2060 }
2061 if matches!(
2062 status.domain_status,
2063 DirectiveDomainStatus::Failed | DirectiveDomainStatus::Rejected
2064 ) || matches!(
2065 status.delivery_status,
2066 DirectiveDeliveryStatus::CoreRejected
2067 | DirectiveDeliveryStatus::Reverted
2068 | DirectiveDeliveryStatus::Expired
2069 | DirectiveDeliveryStatus::DeadLettered
2070 ) {
2071 return TeeApiWalletApprovalProgress::Failed;
2072 }
2073 TeeApiWalletApprovalProgress::Pending
2074}
2075
2076#[derive(Debug, Clone)]
2078pub struct TeeApiWalletEnrollment {
2079 pub api_wallet: AccountAddress,
2081 pub api_wallet_name: String,
2082 pub directive_id: Option<String>,
2084}
2085
2086#[derive(Debug, Clone, Copy)]
2088pub struct TeeApiWalletEnrollmentPolling {
2089 pub interval: Duration,
2090 pub attempts: u32,
2091}
2092
2093impl Default for TeeApiWalletEnrollmentPolling {
2094 fn default() -> Self {
2095 Self {
2096 interval: Duration::from_secs(2),
2097 attempts: 60,
2098 }
2099 }
2100}
2101
2102pub fn resolve_hypercall_builder_address(
2104 exchange_info: &ExchangeInfoResponse,
2105) -> Result<AccountAddress> {
2106 let configured = exchange_info.hl_builder_address.as_deref().ok_or_else(|| {
2107 ClientError::InvalidInput("exchange-info does not publish hl_builder_address".into())
2108 })?;
2109 let builder: AccountAddress = configured
2110 .parse()
2111 .map_err(|source| ClientError::invalid_input("hl_builder_address", source))?;
2112 if builder.as_wallet_address().inner() == Address::ZERO {
2113 return Err(ClientError::InvalidInput(
2114 "exchange-info publishes a zero hl_builder_address".into(),
2115 ));
2116 }
2117 Ok(builder)
2118}
2119
2120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2126pub struct HyperliquidLeverage {
2127 pub is_cross: bool,
2128 pub value: u32,
2129}
2130
2131#[derive(Debug, Deserialize)]
2132struct ActiveAssetData {
2133 user: String,
2134 coin: String,
2135 leverage: ActiveAssetLeverage,
2136}
2137
2138#[derive(Debug, Deserialize)]
2139struct ActiveAssetLeverage {
2140 #[serde(rename = "type")]
2141 kind: String,
2142 value: u32,
2143}
2144
2145#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2147pub struct HyperliquidUserRole {
2148 pub role: String,
2149 #[serde(default)]
2150 pub data: Option<HyperliquidUserRoleData>,
2151}
2152
2153#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2154pub struct HyperliquidUserRoleData {
2155 #[serde(default)]
2156 pub user: Option<String>,
2157}
2158
2159impl HyperliquidUserRole {
2160 pub fn is_agent_for(&self, account: AccountAddress) -> bool {
2162 self.role == "agent"
2163 && self
2164 .data
2165 .as_ref()
2166 .and_then(|data| data.user.as_deref())
2167 .and_then(|user| user.parse::<AccountAddress>().ok())
2168 == Some(account)
2169 }
2170}
2171
2172#[derive(Debug, Clone)]
2174pub struct HyperliquidInfoClient {
2175 client: reqwest::Client,
2176 url: String,
2177}
2178
2179impl HyperliquidInfoClient {
2180 pub fn new(url: impl Into<String>) -> Self {
2181 Self {
2182 client: reqwest::Client::builder()
2183 .timeout(Duration::from_secs(15))
2184 .build()
2185 .expect("failed to build reqwest client"),
2186 url: url.into(),
2187 }
2188 }
2189
2190 pub fn mainnet() -> Self {
2191 Self::new(HYPERLIQUID_MAINNET_INFO_URL)
2192 }
2193
2194 pub fn testnet() -> Self {
2195 Self::new(HYPERLIQUID_TESTNET_INFO_URL)
2196 }
2197
2198 pub fn for_chain_id(chain_id: u64) -> Result<Self> {
2200 match chain_id {
2201 999 => Ok(Self::mainnet()),
2202 998 => Ok(Self::testnet()),
2203 _ => Err(ClientError::InvalidInput(format!(
2204 "unsupported Hyperliquid chain id: {chain_id}"
2205 ))),
2206 }
2207 }
2208
2209 async fn post<T: serde::de::DeserializeOwned>(
2210 &self,
2211 body: serde_json::Value,
2212 action: &str,
2213 ) -> Result<T> {
2214 HypercallClient::send_reqwest_json(self.client.post(&self.url).json(&body), action).await
2215 }
2216
2217 pub async fn user_role(&self, address: AccountAddress) -> Result<HyperliquidUserRole> {
2219 self.post(
2220 serde_json::json!({"type": "userRole", "user": address.to_string()}),
2221 "read Hyperliquid user role",
2222 )
2223 .await
2224 }
2225
2226 pub async fn is_tee_api_wallet_active(
2229 &self,
2230 account: AccountAddress,
2231 api_wallet: AccountAddress,
2232 ) -> Result<bool> {
2233 Ok(self.user_role(api_wallet).await?.is_agent_for(account))
2234 }
2235
2236 pub async fn active_asset_leverage(
2239 &self,
2240 account: AccountAddress,
2241 coin: &str,
2242 ) -> Result<HyperliquidLeverage> {
2243 let data: ActiveAssetData = self
2244 .post(
2245 serde_json::json!({"type": "activeAssetData", "user": account.to_string(), "coin": coin}),
2246 "read Hyperliquid active asset data",
2247 )
2248 .await?;
2249 let echoed_user = data.user.parse::<AccountAddress>().ok();
2250 if echoed_user != Some(account) || data.coin != coin {
2251 return Err(ClientError::Api {
2252 status: 200,
2253 message: "Hyperliquid returned leverage for a different account or market".into(),
2254 });
2255 }
2256 let is_cross = match data.leverage.kind.as_str() {
2257 "cross" => true,
2258 "isolated" => false,
2259 _ => {
2260 return Err(ClientError::Api {
2261 status: 200,
2262 message: "Hyperliquid returned an invalid leverage setting".into(),
2263 })
2264 }
2265 };
2266 if data.leverage.value < 1 {
2267 return Err(ClientError::Api {
2268 status: 200,
2269 message: "Hyperliquid returned an invalid leverage setting".into(),
2270 });
2271 }
2272 Ok(HyperliquidLeverage {
2273 is_cross,
2274 value: data.leverage.value,
2275 })
2276 }
2277}
2278
2279fn approval_typed_data_mismatch(field: &str) -> ClientError {
2284 ClientError::InvalidInput(format!(
2285 "TEE API wallet approval typed data does not match the package: {field}"
2286 ))
2287}
2288
2289fn validate_approval_typed_data(challenge: &TeeApiWalletApprovalChallenge) -> Result<()> {
2290 let typed = &challenge.package.typed_data;
2291 if typed["primaryType"] != "HLAddApiWallet" {
2292 return Err(approval_typed_data_mismatch("primaryType"));
2293 }
2294 if typed["domain"]["name"] != HYPERCALL_MANAGER_DOMAIN {
2295 return Err(approval_typed_data_mismatch("domain.name"));
2296 }
2297 let message = &typed["message"];
2298 let same_address = |value: &serde_json::Value, expected: WalletAddress| {
2299 value
2300 .as_str()
2301 .and_then(|text| text.parse::<WalletAddress>().ok())
2302 == Some(expected)
2303 };
2304 if !same_address(&message["account"], challenge.account.into_wallet_address()) {
2305 return Err(approval_typed_data_mismatch("message.account"));
2306 }
2307 let nonce = match &message["nonce"] {
2308 serde_json::Value::Number(number) => number.as_u64(),
2309 serde_json::Value::String(text) => text.parse().ok(),
2310 _ => None,
2311 };
2312 if nonce != Some(challenge.package.nonce) {
2313 return Err(approval_typed_data_mismatch("message.nonce"));
2314 }
2315 let action = &message["action"];
2316 if !same_address(
2317 &action["apiWalletAddress"],
2318 challenge.package.api_wallet_address,
2319 ) {
2320 return Err(approval_typed_data_mismatch(
2321 "message.action.apiWalletAddress",
2322 ));
2323 }
2324 if action["apiWalletName"] != challenge.package.api_wallet_name.as_str() {
2325 return Err(approval_typed_data_mismatch("message.action.apiWalletName"));
2326 }
2327 Ok(())
2328}
2329
2330fn onchain_error(
2331 operation: impl Into<String>,
2332 source: impl std::error::Error + Send + Sync + 'static,
2333) -> ClientError {
2334 ClientError::Onchain {
2335 operation: operation.into(),
2336 source: Box::new(source),
2337 }
2338}
2339
2340fn is_missing_function_revert(error: &alloy::contract::Error) -> bool {
2343 match error.as_revert_data() {
2344 Some(data) => data.is_empty(),
2345 None => error
2346 .to_string()
2347 .to_ascii_lowercase()
2348 .contains("execution reverted"),
2349 }
2350}
2351
2352impl HypercallClient {
2353 pub async fn server_now_ms(&self) -> Result<u64> {
2356 let offset = match self.server_clock.cached_offset() {
2357 Some(offset) => offset,
2358 None => {
2359 let sent_ms = local_now_ms();
2360 let response = self.request(Method::GET, "/health").send().await?;
2361 let received_ms = local_now_ms();
2362 let date = response
2363 .headers()
2364 .get(reqwest::header::DATE)
2365 .and_then(|value| value.to_str().ok())
2366 .ok_or_else(|| ClientError::Api {
2367 status: response.status().as_u16(),
2368 message: "/health response carries no Date header to stamp TEE nonces"
2369 .into(),
2370 })?;
2371 let offset =
2372 server_clock_offset_ms(date, sent_ms, received_ms).ok_or_else(|| {
2373 ClientError::Api {
2374 status: response.status().as_u16(),
2375 message: format!("/health Date header is not an HTTP date: {date}"),
2376 }
2377 })?;
2378 self.server_clock.store(offset);
2379 offset
2380 }
2381 };
2382 u64::try_from(local_now_ms() + offset).map_err(|_| ClientError::ArithmeticOverflow {
2383 operation: "server clock",
2384 })
2385 }
2386
2387 pub async fn next_tee_perp_nonce(&self, signer: AccountAddress) -> Result<u64> {
2390 let now = self.server_now_ms().await?;
2391 Ok(next_nonce_at(signer.as_wallet_address().inner(), now))
2392 }
2393
2394 pub(crate) async fn resolve_tee_nonce(
2395 &self,
2396 signer: AccountAddress,
2397 nonce: Option<u64>,
2398 ) -> Result<u64> {
2399 match nonce {
2400 Some(nonce) => Ok(nonce),
2401 None => self.next_tee_perp_nonce(signer).await,
2402 }
2403 }
2404
2405 async fn post_tee<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2406 where
2407 T: serde::de::DeserializeOwned,
2408 B: serde::Serialize + ?Sized,
2409 {
2410 Self::send_json_body(self.request(Method::POST, route), body, action).await
2411 }
2412
2413 pub(crate) async fn post_tee_signed<T, B>(
2417 &self,
2418 route: &str,
2419 body: &B,
2420 action: &str,
2421 ) -> Result<T>
2422 where
2423 T: serde::de::DeserializeOwned,
2424 B: SignedTeeSubmission,
2425 {
2426 let request_json = sonic_rs::to_string(body)
2427 .map_err(|source| ClientError::invalid_input("TEE request body", source))?;
2428 self.send_tee_submission(route, request_json, body.nonce(), action, false)
2429 .await
2430 }
2431
2432 async fn send_tee_submission<T>(
2433 &self,
2434 route: &str,
2435 request_json: String,
2436 nonce: u64,
2437 action: &str,
2438 resend: bool,
2439 ) -> Result<T>
2440 where
2441 T: serde::de::DeserializeOwned,
2442 {
2443 let request = self
2444 .request(Method::POST, route)
2445 .header(reqwest::header::CONTENT_TYPE, "application/json")
2446 .body(request_json.clone());
2447 match Self::send_reqwest_json(request, action).await {
2448 Err(error) if resend || tee_submission_is_ambiguous(&error) => {
2452 Err(ClientError::TeeSubmissionAmbiguous {
2453 action: action.to_owned(),
2454 route: route.to_owned(),
2455 nonce,
2456 request_json,
2457 source: Box::new(error),
2458 })
2459 }
2460 result => result,
2461 }
2462 }
2463
2464 pub async fn resend_tee_submission<T>(&self, route: &str, request_json: &str) -> Result<T>
2475 where
2476 T: serde::de::DeserializeOwned,
2477 {
2478 let nonce = serde_json::from_str::<serde_json::Value>(request_json)
2479 .ok()
2480 .and_then(|body| match &body["nonce"] {
2481 serde_json::Value::Number(number) => number.as_u64(),
2482 serde_json::Value::String(text) => text.parse().ok(),
2483 _ => None,
2484 })
2485 .ok_or_else(|| {
2486 ClientError::InvalidInput("request_json carries no signed nonce".into())
2487 })?;
2488 self.send_tee_submission(
2489 route,
2490 request_json.to_owned(),
2491 nonce,
2492 "resend TEE submission",
2493 true,
2494 )
2495 .await
2496 }
2497
2498 pub async fn place_tee_perp_limit_order<S>(
2502 &self,
2503 signer: &S,
2504 params: PerpLimitOrderParams,
2505 ) -> Result<TeePerpOrderResponse>
2506 where
2507 S: PerpDirectiveSigner + ?Sized,
2508 {
2509 let nonce = self
2510 .resolve_tee_nonce(signer.address(), params.nonce)
2511 .await?;
2512 let action = HlLimitOrderAction {
2513 asset: params.asset,
2514 is_buy: matches!(params.side, Side::Buy),
2515 limit_px: to_perp_units(params.price, "perp limit price")?,
2516 sz: to_perp_units(params.size, "perp size")?,
2517 reduce_only: params.reduce_only,
2518 tif: params.tif,
2519 cloid: nonzero_cloid(params.client_order_id.unwrap_or(u128::from(nonce)))?,
2520 };
2521 let signature = signer
2522 .sign_perp_limit_order_payload(PerpLimitOrderSignature {
2523 account: params.account,
2524 nonce,
2525 action,
2526 })
2527 .await?;
2528 let request = DirectiveSubmitRequest {
2529 account: params.account.into_wallet_address(),
2530 nonce,
2531 action,
2532 signature,
2533 };
2534 self.post_tee_signed(
2535 TEE_PERP_ORDER_SUBMIT_ROUTE,
2536 &request,
2537 "submit TEE perp order",
2538 )
2539 .await
2540 }
2541
2542 pub async fn place_tee_perp_market_order<S>(
2544 &self,
2545 signer: &S,
2546 params: TeePerpMarketOrderParams,
2547 ) -> Result<TeePerpOrderResponse>
2548 where
2549 S: PerpDirectiveSigner + ?Sized,
2550 {
2551 let size_decimals = validate_size_decimals(params.size_decimals)?;
2552 if params.size.normalize().scale() > size_decimals {
2553 return Err(ClientError::InvalidInput(format!(
2554 "size {} has more than {size_decimals} decimals",
2555 params.size
2556 )));
2557 }
2558 let price = perp_market_limit_price(
2559 params.reference_price,
2560 params.side,
2561 size_decimals,
2562 params.slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2563 )?;
2564 self.place_tee_perp_limit_order(
2565 signer,
2566 PerpLimitOrderParams {
2567 account: params.account,
2568 asset: params.asset,
2569 side: params.side,
2570 price,
2571 size: params.size,
2572 tif: PerpTimeInForce::Ioc,
2573 reduce_only: params.reduce_only,
2574 client_order_id: params.client_order_id,
2575 nonce: params.nonce,
2576 },
2577 )
2578 .await
2579 }
2580
2581 pub async fn place_tee_perp_trigger_order<S>(
2583 &self,
2584 signer: &S,
2585 params: TeePerpTriggerOrderParams,
2586 ) -> Result<TeePerpOrderBatchResponse>
2587 where
2588 S: TeePerpSigner + ?Sized,
2589 {
2590 let (limit_price, is_market) = match params.execution {
2591 TeePerpTriggerExecution::Market {
2592 size_decimals,
2593 slippage_bps,
2594 } => (
2595 perp_market_limit_price(
2596 params.trigger_price,
2597 params.side,
2598 size_decimals,
2599 slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2600 )?,
2601 true,
2602 ),
2603 TeePerpTriggerExecution::Limit { price } => (price, false),
2604 };
2605 let nonce = self
2606 .resolve_tee_nonce(signer.address(), params.nonce)
2607 .await?;
2608 let cloid = match params.client_order_id {
2609 Some(cloid) => cloid,
2610 None => tee_perp_batch_cloid(nonce, 0)?,
2611 };
2612 let order = tee_perp_trigger_order_wire(
2613 params.asset,
2614 params.side,
2615 params.trigger_price,
2616 limit_price,
2617 params.size,
2618 is_market,
2619 params.tpsl,
2620 params.reduce_only,
2621 cloid,
2622 )?;
2623 let signature = signer
2624 .sign_tee_perp_trigger_order_payload(TeePerpTriggerOrderSignature {
2625 account: params.account,
2626 nonce,
2627 order,
2628 })
2629 .await?;
2630 let request = DirectiveSubmitRequest {
2631 account: params.account.into_wallet_address(),
2632 nonce,
2633 action: order,
2634 signature,
2635 };
2636 self.post_tee_signed(
2637 TEE_PERP_TRIGGER_ORDER_SUBMIT_ROUTE,
2638 &request,
2639 "submit TEE perp trigger order",
2640 )
2641 .await
2642 }
2643
2644 pub async fn place_tee_perp_order_batch<S>(
2646 &self,
2647 signer: &S,
2648 params: TeePerpOrderBatchParams,
2649 ) -> Result<TeePerpOrderBatchResponse>
2650 where
2651 S: TeePerpSigner + ?Sized,
2652 {
2653 validate_batch(¶ms.batch)?;
2654 let signature = signer
2655 .sign_tee_perp_order_batch_payload(TeePerpOrderBatchSignature {
2656 account: params.account,
2657 nonce: params.nonce,
2658 batch: ¶ms.batch,
2659 })
2660 .await?;
2661 let request = DirectiveSubmitRequest {
2662 account: params.account.into_wallet_address(),
2663 nonce: params.nonce,
2664 action: params.batch,
2665 signature,
2666 };
2667 self.post_tee_signed(
2668 TEE_PERP_ORDER_BATCH_SUBMIT_ROUTE,
2669 &request,
2670 "submit TEE perp order batch",
2671 )
2672 .await
2673 }
2674
2675 pub async fn place_tee_perp_bracket_order<S>(
2677 &self,
2678 signer: &S,
2679 params: TeePerpBracketOrderParams,
2680 ) -> Result<TeePerpOrderBatchResponse>
2681 where
2682 S: TeePerpSigner + ?Sized,
2683 {
2684 let nonce = self
2685 .resolve_tee_nonce(signer.address(), params.nonce)
2686 .await?;
2687 let batch = build_tee_perp_bracket_batch(
2688 params.entry,
2689 params.take_profit,
2690 params.stop_loss,
2691 nonce,
2692 )?;
2693 self.place_tee_perp_order_batch(
2694 signer,
2695 TeePerpOrderBatchParams {
2696 account: params.account,
2697 nonce,
2698 batch,
2699 },
2700 )
2701 .await
2702 }
2703
2704 pub async fn place_tee_perp_position_tpsl<S>(
2706 &self,
2707 signer: &S,
2708 params: TeePerpPositionTpslParams,
2709 ) -> Result<TeePerpOrderBatchResponse>
2710 where
2711 S: TeePerpSigner + ?Sized,
2712 {
2713 let nonce = self
2714 .resolve_tee_nonce(signer.address(), params.nonce)
2715 .await?;
2716 let batch = build_tee_perp_position_tpsl_batch(
2717 params.asset,
2718 params.position_side,
2719 params.size,
2720 params.take_profit,
2721 params.stop_loss,
2722 nonce,
2723 )?;
2724 self.place_tee_perp_order_batch(
2725 signer,
2726 TeePerpOrderBatchParams {
2727 account: params.account,
2728 nonce,
2729 batch,
2730 },
2731 )
2732 .await
2733 }
2734
2735 pub async fn place_tee_perp_scale_order<S>(
2737 &self,
2738 signer: &S,
2739 params: TeePerpScaleOrderParams,
2740 ) -> Result<TeePerpOrderBatchResponse>
2741 where
2742 S: TeePerpSigner + ?Sized,
2743 {
2744 let nonce = self
2745 .resolve_tee_nonce(signer.address(), params.nonce)
2746 .await?;
2747 let batch = build_tee_perp_scale_batch(
2748 params.asset,
2749 params.side,
2750 ¶ms.legs,
2751 params.tif,
2752 params.reduce_only,
2753 nonce,
2754 )?;
2755 self.place_tee_perp_order_batch(
2756 signer,
2757 TeePerpOrderBatchParams {
2758 account: params.account,
2759 nonce,
2760 batch,
2761 },
2762 )
2763 .await
2764 }
2765
2766 pub async fn cancel_tee_perp_order_by_oid<S>(
2768 &self,
2769 signer: &S,
2770 params: PerpCancelByOidParams,
2771 ) -> Result<TeePerpVenueActionResponse>
2772 where
2773 S: PerpDirectiveSigner + ?Sized,
2774 {
2775 if params.order_id == 0 {
2776 return Err(ClientError::InvalidInput("oid must not be zero".into()));
2777 }
2778 let nonce = self
2779 .resolve_tee_nonce(signer.address(), params.nonce)
2780 .await?;
2781 let action = HlCancelByOidAction {
2782 asset: params.asset,
2783 oid: params.order_id,
2784 };
2785 let signature = signer
2786 .sign_perp_cancel_by_oid_payload(PerpCancelByOidSignature {
2787 account: params.account,
2788 nonce,
2789 action,
2790 })
2791 .await?;
2792 let request = DirectiveSubmitRequest {
2793 account: params.account.into_wallet_address(),
2794 nonce,
2795 action,
2796 signature,
2797 };
2798 self.post_tee_signed(
2799 TEE_PERP_CANCEL_BY_OID_SUBMIT_ROUTE,
2800 &request,
2801 "submit TEE perp cancel by oid",
2802 )
2803 .await
2804 }
2805
2806 pub async fn cancel_tee_perp_order_by_cloid<S>(
2808 &self,
2809 signer: &S,
2810 params: PerpCancelByCloidParams,
2811 ) -> Result<TeePerpCancelResponse>
2812 where
2813 S: PerpDirectiveSigner + ?Sized,
2814 {
2815 let nonce = self
2816 .resolve_tee_nonce(signer.address(), params.nonce)
2817 .await?;
2818 let action = HlCancelByCloidAction {
2819 asset: params.asset,
2820 cloid: nonzero_cloid(params.client_order_id)?,
2821 };
2822 let signature = signer
2823 .sign_perp_cancel_by_cloid_payload(PerpCancelByCloidSignature {
2824 account: params.account,
2825 nonce,
2826 action,
2827 })
2828 .await?;
2829 let request = DirectiveSubmitRequest {
2830 account: params.account.into_wallet_address(),
2831 nonce,
2832 action,
2833 signature,
2834 };
2835 self.post_tee_signed(
2836 TEE_PERP_CANCEL_SUBMIT_ROUTE,
2837 &request,
2838 "submit TEE perp cancel by cloid",
2839 )
2840 .await
2841 }
2842
2843 pub async fn update_tee_perp_leverage<S>(
2846 &self,
2847 signer: &S,
2848 params: TeePerpLeverageParams,
2849 ) -> Result<TeePerpLeverageResponse>
2850 where
2851 S: TeePerpSigner + ?Sized,
2852 {
2853 if params.leverage == 0 {
2854 return Err(ClientError::InvalidInput(
2855 "leverage must be greater than zero".into(),
2856 ));
2857 }
2858 let nonce = self
2859 .resolve_tee_nonce(signer.address(), params.nonce)
2860 .await?;
2861 let action = TeePerpLeverageAction {
2862 asset: params.asset,
2863 is_cross: params.is_cross,
2864 leverage: params.leverage,
2865 };
2866 let signature = signer
2867 .sign_tee_perp_leverage_payload(TeePerpLeverageSignature {
2868 account: params.account,
2869 nonce,
2870 action,
2871 })
2872 .await?;
2873 let request = DirectiveSubmitRequest {
2874 account: params.account.into_wallet_address(),
2875 nonce,
2876 action,
2877 signature,
2878 };
2879 self.post_tee_signed(
2880 TEE_PERP_LEVERAGE_SUBMIT_ROUTE,
2881 &request,
2882 "submit TEE perp leverage",
2883 )
2884 .await
2885 }
2886
2887 pub async fn modify_tee_perp_order<S>(
2895 &self,
2896 signer: &S,
2897 params: TeePerpModifyParams,
2898 ) -> Result<TeePerpModifyResponse>
2899 where
2900 S: TeePerpSigner + ?Sized,
2901 {
2902 let action = params.replacement.to_action()?;
2903 let nonce = self
2904 .resolve_tee_nonce(signer.address(), params.nonce)
2905 .await?;
2906 let signature = signer
2907 .sign_tee_perp_modify_payload(TeePerpModifySignature {
2908 account: params.account,
2909 nonce,
2910 action,
2911 })
2912 .await?;
2913 let request = DirectiveSubmitRequest {
2914 account: params.account.into_wallet_address(),
2915 nonce,
2916 action,
2917 signature,
2918 };
2919 self.post_tee_signed(
2920 TEE_PERP_ORDER_MODIFY_ROUTE,
2921 &request,
2922 "submit TEE perp modify",
2923 )
2924 .await
2925 }
2926
2927 pub async fn batch_modify_tee_perp_orders<S>(
2944 &self,
2945 signer: &S,
2946 params: TeePerpBatchModifyParams,
2947 ) -> Result<TeePerpBatchModifyResponse>
2948 where
2949 S: TeePerpSigner + ?Sized,
2950 {
2951 let batch = build_tee_perp_batch_modify(¶ms.replacements, params.max_children)?;
2952 let nonce = self
2953 .resolve_tee_nonce(signer.address(), params.nonce)
2954 .await?;
2955 let signature = signer
2956 .sign_tee_perp_batch_modify_payload(TeePerpBatchModifySignature {
2957 account: params.account,
2958 nonce,
2959 batch: &batch,
2960 })
2961 .await?;
2962 let request = DirectiveSubmitRequest {
2963 account: params.account.into_wallet_address(),
2964 nonce,
2965 action: batch,
2966 signature,
2967 };
2968 self.post_tee_signed(
2969 TEE_PERP_ORDER_BATCH_MODIFY_ROUTE,
2970 &request,
2971 "submit TEE perp batch modify",
2972 )
2973 .await
2974 }
2975
2976 pub async fn place_tee_perp_twap_order<S>(
2984 &self,
2985 signer: &S,
2986 params: TeePerpTwapParams,
2987 ) -> Result<TeePerpTwapResponse>
2988 where
2989 S: TeePerpSigner + ?Sized,
2990 {
2991 let action = TeePerpTwapAction {
2992 asset: params.asset,
2993 is_buy: matches!(params.side, Side::Buy),
2994 sz: to_perp_units(params.size, "size")?,
2995 reduce_only: params.reduce_only,
2996 minutes: params.minutes,
2997 randomize: params.randomize,
2998 };
2999 validate_twap_action(&action)?;
3000 let nonce = self
3001 .resolve_tee_nonce(signer.address(), params.nonce)
3002 .await?;
3003 let signature = signer
3004 .sign_tee_perp_twap_payload(TeePerpTwapSignature {
3005 account: params.account,
3006 nonce,
3007 action,
3008 })
3009 .await?;
3010 let request = DirectiveSubmitRequest {
3011 account: params.account.into_wallet_address(),
3012 nonce,
3013 action,
3014 signature,
3015 };
3016 self.post_tee_signed(TEE_PERP_TWAP_SUBMIT_ROUTE, &request, "submit TEE perp TWAP")
3017 .await
3018 }
3019
3020 pub async fn cancel_tee_perp_twap<S>(
3023 &self,
3024 signer: &S,
3025 params: TeePerpTwapCancelParams,
3026 ) -> Result<TeePerpVenueActionResponse>
3027 where
3028 S: TeePerpSigner + ?Sized,
3029 {
3030 if params.twap_id == 0 {
3031 return Err(ClientError::InvalidInput("twap_id must not be zero".into()));
3032 }
3033 let nonce = self
3034 .resolve_tee_nonce(signer.address(), params.nonce)
3035 .await?;
3036 let action = TeePerpTwapCancelAction {
3037 asset: params.asset,
3038 twap_id: params.twap_id,
3039 };
3040 let signature = signer
3041 .sign_tee_perp_twap_cancel_payload(TeePerpTwapCancelSignature {
3042 account: params.account,
3043 nonce,
3044 action,
3045 })
3046 .await?;
3047 let request = DirectiveSubmitRequest {
3048 account: params.account.into_wallet_address(),
3049 nonce,
3050 action,
3051 signature,
3052 };
3053 self.post_tee_signed(
3054 TEE_PERP_TWAP_CANCEL_ROUTE,
3055 &request,
3056 "submit TEE perp TWAP cancel",
3057 )
3058 .await
3059 }
3060
3061 pub async fn preview_tee_perp_action(
3064 &self,
3065 request: &PerpPreviewRequest,
3066 ) -> Result<PerpPreviewResponse> {
3067 let envelope: ApiResponse<PerpPreviewResponse> = self
3068 .post_tee(TEE_PERP_PREVIEW_ROUTE, request, "preview TEE perp action")
3069 .await?;
3070 if !envelope.success {
3071 return Err(ClientError::Api {
3072 status: 200,
3073 message: envelope
3074 .error
3075 .unwrap_or_else(|| "TEE perp preview failed".into()),
3076 });
3077 }
3078 envelope.data.ok_or_else(|| ClientError::Api {
3079 status: 200,
3080 message: "TEE perp preview returned no data".into(),
3081 })
3082 }
3083
3084 pub async fn get_tee_perp_markets(&self) -> Result<TeePerpMarketsResponse> {
3086 Self::send_reqwest_json(
3087 self.request(Method::GET, TEE_PERP_MARKETS_ROUTE),
3088 "get TEE perp markets",
3089 )
3090 .await
3091 }
3092
3093 pub async fn request_tee_api_wallet_approval<S>(
3096 &self,
3097 manager: &S,
3098 account: AccountAddress,
3099 ) -> Result<TeeApiWalletApprovalChallenge>
3100 where
3101 S: TeeApiWalletManagerSigner + ?Sized,
3102 {
3103 let timestamp = i64::try_from(self.server_now_ms().await? / 1_000).map_err(|_| {
3104 ClientError::ArithmeticOverflow {
3105 operation: "authentication timestamp",
3106 }
3107 })?;
3108 let manager_address = manager.address();
3109 let authentication_signature = manager.sign_authentication_payload(timestamp).await?;
3110 let request = TeeApiWalletApprovalRequest {
3111 account: account.into_wallet_address(),
3112 manager: manager_address.into_wallet_address(),
3113 timestamp,
3114 signature: authentication_signature.clone(),
3115 };
3116 let package: TeeApiWalletApprovalPackage = self
3117 .post_tee(
3118 TEE_API_WALLET_APPROVAL_REQUEST_ROUTE,
3119 &request,
3120 "request TEE API wallet approval",
3121 )
3122 .await?;
3123 Ok(TeeApiWalletApprovalChallenge {
3124 account,
3125 manager: manager_address,
3126 timestamp,
3127 authentication_signature,
3128 package,
3129 })
3130 }
3131
3132 pub async fn submit_tee_api_wallet_approval<S>(
3135 &self,
3136 manager: &S,
3137 challenge: &TeeApiWalletApprovalChallenge,
3138 ) -> Result<DirectiveSubmitResponse>
3139 where
3140 S: TeeApiWalletManagerSigner + ?Sized,
3141 {
3142 validate_approval_typed_data(challenge)?;
3143 let signature = manager
3144 .sign_tee_api_wallet_approval_payload(TeeApiWalletApprovalSignature {
3145 account: challenge.account,
3146 nonce: challenge.package.nonce,
3147 api_wallet_address: AccountAddress::from(
3148 challenge.package.api_wallet_address.inner(),
3149 ),
3150 api_wallet_name: &challenge.package.api_wallet_name,
3151 })
3152 .await?;
3153 let request = TeeApiWalletApprovalSubmitRequest {
3154 account: challenge.account.into_wallet_address(),
3155 manager: challenge.manager.into_wallet_address(),
3156 timestamp: challenge.timestamp,
3157 authentication_signature: challenge.authentication_signature.clone(),
3158 tee_wallet_id: challenge.package.tee_wallet_id,
3159 nonce: challenge.package.nonce,
3160 signature,
3161 };
3162 self.post_tee_signed(
3163 TEE_API_WALLET_APPROVAL_ROUTE,
3164 &request,
3165 "submit TEE API wallet approval",
3166 )
3167 .await
3168 }
3169
3170 pub async fn enroll_tee_api_wallet<S>(
3175 &self,
3176 manager: &S,
3177 account: AccountAddress,
3178 hyperliquid: &HyperliquidInfoClient,
3179 polling: TeeApiWalletEnrollmentPolling,
3180 ) -> Result<TeeApiWalletEnrollment>
3181 where
3182 S: TeeApiWalletManagerSigner + ?Sized,
3183 {
3184 let challenge = self
3185 .request_tee_api_wallet_approval(manager, account)
3186 .await?;
3187 let api_wallet = AccountAddress::from(challenge.package.api_wallet_address.inner());
3188 let api_wallet_name = challenge.package.api_wallet_name.clone();
3189 if hyperliquid
3190 .is_tee_api_wallet_active(account, api_wallet)
3191 .await?
3192 {
3193 return Ok(TeeApiWalletEnrollment {
3194 api_wallet,
3195 api_wallet_name,
3196 directive_id: None,
3197 });
3198 }
3199 let response = self
3200 .submit_tee_api_wallet_approval(manager, &challenge)
3201 .await?;
3202 if let Some(rejection) = &response.rejection {
3203 return Err(ClientError::Api {
3204 status: 200,
3205 message: format!(
3206 "TEE API wallet approval rejected ({}): {}",
3207 rejection.code, rejection.message
3208 ),
3209 });
3210 }
3211 let mut finalized = false;
3212 for _ in 0..polling.attempts {
3213 if let Ok(status) = self.get_directive_status(&response.directive_id).await {
3215 match tee_api_wallet_approval_progress(&status) {
3216 TeeApiWalletApprovalProgress::Finalized => {
3217 finalized = true;
3218 break;
3219 }
3220 TeeApiWalletApprovalProgress::Failed => {
3221 return Err(ClientError::Api {
3222 status: 200,
3223 message: format!(
3224 "TEE API wallet approval {} failed: domain {:?}, delivery {:?}",
3225 response.directive_id, status.domain_status, status.delivery_status
3226 ),
3227 });
3228 }
3229 TeeApiWalletApprovalProgress::Pending => {}
3230 }
3231 }
3232 tokio::time::sleep(polling.interval).await;
3233 }
3234 if !finalized {
3235 return Err(ClientError::Api {
3236 status: 200,
3237 message: format!(
3238 "TEE API wallet approval {} is still pending",
3239 response.directive_id
3240 ),
3241 });
3242 }
3243 if !hyperliquid
3244 .is_tee_api_wallet_active(account, api_wallet)
3245 .await?
3246 {
3247 return Err(ClientError::Api {
3248 status: 200,
3249 message: "Hyperliquid did not bind the finalized TEE API wallet to this account"
3250 .into(),
3251 });
3252 }
3253 Ok(TeeApiWalletEnrollment {
3254 api_wallet,
3255 api_wallet_name,
3256 directive_id: Some(response.directive_id),
3257 })
3258 }
3259
3260 pub async fn approve_hypercall_builder(
3268 &self,
3269 manager: &HypercallWallet,
3270 params: ApproveHypercallBuilderParams,
3271 ) -> Result<B256> {
3272 let builder = match params.builder {
3273 Some(builder) => builder,
3274 None => resolve_hypercall_builder_address(&self.get_exchange_info().await?)?,
3275 };
3276 let builder = builder.as_wallet_address().inner();
3277 if builder == Address::ZERO {
3278 return Err(ClientError::InvalidInput("builder must not be zero".into()));
3279 }
3280 let rpc_url = params
3281 .rpc_url
3282 .parse()
3283 .map_err(|source| ClientError::invalid_input("HyperEVM RPC URL", source))?;
3284 let provider = ProviderBuilder::new()
3285 .wallet(manager.ethereum_wallet())
3286 .connect_http(rpc_url);
3287 let rpc_chain_id = provider
3288 .get_chain_id()
3289 .await
3290 .map_err(|error| onchain_error("read HyperEVM chain ID", error))?;
3291 if rpc_chain_id != manager.chain_id() {
3292 return Err(ClientError::InvalidInput(format!(
3293 "HyperEVM RPC chain ID {rpc_chain_id} does not match wallet chain ID {}",
3294 manager.chain_id()
3295 )));
3296 }
3297 let manager_address = manager.address.as_wallet_address().inner();
3298 let balance = provider
3299 .get_balance(manager_address)
3300 .await
3301 .map_err(|error| onchain_error("read manager HYPE balance", error))?;
3302 if balance.is_zero() {
3303 return Err(ClientError::InvalidInput(
3304 "the manager wallet needs a small amount of HYPE on HyperEVM to pay the network fee"
3305 .into(),
3306 ));
3307 }
3308 let account = HypercallAccountBuilderApproval::new(
3309 params.account.as_wallet_address().inner(),
3310 &provider,
3311 );
3312 let call = account.approveZeroFeeBuilder(builder).from(manager_address);
3313 if let Err(error) = call.call().await {
3314 if is_missing_function_revert(&error) {
3315 return Err(ClientError::InvalidInput(
3316 "this Account implementation predates approveZeroFeeBuilder (needs 0.2.4); trading cannot be enabled yet".into(),
3317 ));
3318 }
3319 return Err(onchain_error("simulate approveZeroFeeBuilder", error));
3320 }
3321 let submission_lock = evm_submission_lock(manager_address);
3322 let _guard = submission_lock.lock().await;
3323 let receipt = call
3324 .send()
3325 .await
3326 .map_err(|error| onchain_error("submit approveZeroFeeBuilder", error))?
3327 .with_timeout(Some(Duration::from_secs(60)))
3328 .get_receipt()
3329 .await
3330 .map_err(|error| onchain_error("confirm approveZeroFeeBuilder", error))?;
3331 if !receipt.status() {
3332 return Err(ClientError::TransactionReverted {
3333 operation: "approveZeroFeeBuilder",
3334 transaction_hash: Some(receipt.transaction_hash),
3335 });
3336 }
3337 Ok(receipt.transaction_hash)
3338 }
3339}
3340
3341#[cfg(test)]
3342#[path = "tee_perp_test.rs"]
3343mod tests;
3344
3345#[cfg(test)]
3346#[path = "tee_perp_modify_test.rs"]
3347mod modify_tests;