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