opentool 0.17.1 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -681,274 +681,633 @@ function assertPositiveNumber(value, label) {
681
681
  }
682
682
  }
683
683
 
684
- // src/adapters/hyperliquid/info.ts
685
- async function postInfo(environment, payload) {
686
- const baseUrl = API_BASES[environment];
687
- const response = await fetch(`${baseUrl}/info`, {
688
- method: "POST",
689
- headers: { "content-type": "application/json" },
690
- body: JSON.stringify(payload)
691
- });
692
- const data = await response.json().catch(() => null);
693
- if (!response.ok) {
694
- throw new HyperliquidApiError(
695
- "Hyperliquid info request failed.",
696
- data ?? { status: response.status }
697
- );
698
- }
699
- return data;
684
+ // src/adapters/hyperliquid/symbols.ts
685
+ var UNKNOWN_SYMBOL2 = "UNKNOWN";
686
+ function extractHyperliquidDex(symbol) {
687
+ const idx = symbol.indexOf(":");
688
+ if (idx <= 0) return null;
689
+ const dex = symbol.slice(0, idx).trim().toLowerCase();
690
+ return dex || null;
700
691
  }
701
- var HyperliquidInfoClient = class {
702
- constructor(environment = "mainnet") {
703
- this.environment = environment;
704
- }
705
- meta() {
706
- return fetchHyperliquidMeta(this.environment);
707
- }
708
- metaAndAssetCtxs() {
709
- return fetchHyperliquidMetaAndAssetCtxs(this.environment);
710
- }
711
- spotMeta() {
712
- return fetchHyperliquidSpotMeta(this.environment);
713
- }
714
- spotMetaAndAssetCtxs() {
715
- return fetchHyperliquidSpotMetaAndAssetCtxs(this.environment);
716
- }
717
- assetCtxs() {
718
- return fetchHyperliquidAssetCtxs(this.environment);
719
- }
720
- spotAssetCtxs() {
721
- return fetchHyperliquidSpotAssetCtxs(this.environment);
722
- }
723
- openOrders(user) {
724
- return fetchHyperliquidOpenOrders({ user, environment: this.environment });
725
- }
726
- frontendOpenOrders(user) {
727
- return fetchHyperliquidFrontendOpenOrders({
728
- user,
729
- environment: this.environment
730
- });
731
- }
732
- orderStatus(user, oid) {
733
- return fetchHyperliquidOrderStatus({
734
- user,
735
- oid,
736
- environment: this.environment
737
- });
738
- }
739
- historicalOrders(user) {
740
- return fetchHyperliquidHistoricalOrders({
741
- user,
742
- environment: this.environment
743
- });
744
- }
745
- userFills(user) {
746
- return fetchHyperliquidUserFills({ user, environment: this.environment });
747
- }
748
- userFillsByTime(user, startTime, endTime) {
749
- return fetchHyperliquidUserFillsByTime({
750
- user,
751
- startTime,
752
- endTime,
753
- environment: this.environment
754
- });
755
- }
756
- userRateLimit(user) {
757
- return fetchHyperliquidUserRateLimit({
758
- user,
759
- environment: this.environment
760
- });
692
+ function parseHyperliquidSymbol(value) {
693
+ if (!value) return null;
694
+ const trimmed = value.trim();
695
+ if (!trimmed) return null;
696
+ if (trimmed.startsWith("@")) {
697
+ return {
698
+ raw: trimmed,
699
+ kind: "spotIndex",
700
+ normalized: trimmed,
701
+ routeTicker: trimmed,
702
+ displaySymbol: trimmed,
703
+ base: null,
704
+ quote: null,
705
+ pair: null,
706
+ dex: null,
707
+ leverageMode: "cross"
708
+ };
761
709
  }
762
- preTransferCheck(user, source) {
763
- return fetchHyperliquidPreTransferCheck({
764
- user,
765
- source,
766
- environment: this.environment
767
- });
710
+ const dex = extractHyperliquidDex(trimmed);
711
+ const pair = resolveHyperliquidPair(trimmed);
712
+ const base = normalizeHyperliquidBaseSymbol(trimmed);
713
+ if (dex) {
714
+ if (!base) return null;
715
+ return {
716
+ raw: trimmed,
717
+ kind: "perp",
718
+ normalized: `${dex}:${base}`,
719
+ routeTicker: `${dex}:${base}`,
720
+ displaySymbol: `${dex.toUpperCase()}:${base}-USDC`,
721
+ base,
722
+ quote: null,
723
+ pair: null,
724
+ dex,
725
+ leverageMode: "isolated"
726
+ };
768
727
  }
769
- spotClearinghouseState(user) {
770
- return fetchHyperliquidSpotClearinghouseState({
771
- user,
772
- environment: this.environment
773
- });
728
+ if (pair) {
729
+ const [pairBase, pairQuote] = pair.split("/");
730
+ return {
731
+ raw: trimmed,
732
+ kind: "spot",
733
+ normalized: pair,
734
+ routeTicker: pair.replace("/", "-"),
735
+ displaySymbol: pair.replace("/", "-"),
736
+ base: pairBase ?? null,
737
+ quote: pairQuote ?? null,
738
+ pair,
739
+ dex: null,
740
+ leverageMode: "cross"
741
+ };
774
742
  }
775
- };
776
- async function fetchHyperliquidMeta(environment = "mainnet") {
777
- return postInfo(environment, { type: "meta" });
743
+ if (!base) return null;
744
+ return {
745
+ raw: trimmed,
746
+ kind: "perp",
747
+ normalized: base,
748
+ routeTicker: base,
749
+ displaySymbol: `${base}-USDC`,
750
+ base,
751
+ quote: null,
752
+ pair: null,
753
+ dex: null,
754
+ leverageMode: "cross"
755
+ };
778
756
  }
779
- async function fetchHyperliquidMetaAndAssetCtxs(environment = "mainnet") {
780
- return postInfo(environment, { type: "metaAndAssetCtxs" });
757
+ function normalizeSpotTokenName2(value) {
758
+ const raw = (value ?? "").trim();
759
+ if (!raw) return "";
760
+ if (raw.endsWith("0") && raw.length > 1) {
761
+ return raw.slice(0, -1);
762
+ }
763
+ return raw;
781
764
  }
782
- async function fetchHyperliquidSpotMeta(environment = "mainnet") {
783
- return postInfo(environment, { type: "spotMeta" });
765
+ function canonicalizeHyperliquidTokenCase(value) {
766
+ const trimmed = value.trim();
767
+ if (!trimmed) return "";
768
+ return trimmed === trimmed.toLowerCase() ? trimmed.toUpperCase() : trimmed;
784
769
  }
785
- async function fetchHyperliquidSpotMetaAndAssetCtxs(environment = "mainnet") {
786
- return postInfo(environment, { type: "spotMetaAndAssetCtxs" });
770
+ function normalizeHyperliquidBaseSymbol(value) {
771
+ if (!value) return null;
772
+ const trimmed = value.trim();
773
+ if (!trimmed) return null;
774
+ const withoutDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
775
+ const base = withoutDex.split("-")[0] ?? withoutDex;
776
+ const baseNoPair = base.split("/")[0] ?? base;
777
+ const normalized = canonicalizeHyperliquidTokenCase(baseNoPair);
778
+ if (!normalized || normalized === UNKNOWN_SYMBOL2) return null;
779
+ return normalized;
787
780
  }
788
- async function fetchHyperliquidAssetCtxs(environment = "mainnet") {
789
- return postInfo(environment, { type: "assetCtxs" });
781
+ function normalizeHyperliquidMetaSymbol(symbol) {
782
+ const trimmed = symbol.trim();
783
+ const noDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
784
+ const noPair = noDex.split("-")[0] ?? noDex;
785
+ return (noPair.split("/")[0] ?? noPair).trim();
790
786
  }
791
- async function fetchHyperliquidSpotAssetCtxs(environment = "mainnet") {
792
- return postInfo(environment, { type: "spotAssetCtxs" });
787
+ function resolveHyperliquidPair(value) {
788
+ if (!value) return null;
789
+ const trimmed = value.trim();
790
+ if (!trimmed) return null;
791
+ const withoutDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
792
+ if (withoutDex.includes("/")) {
793
+ const [base, ...rest] = withoutDex.split("/");
794
+ const quote = rest.join("/").trim();
795
+ if (!base || !quote) return null;
796
+ return `${canonicalizeHyperliquidTokenCase(base)}/${canonicalizeHyperliquidTokenCase(quote)}`;
797
+ }
798
+ if (withoutDex.includes("-")) {
799
+ const [base, ...rest] = withoutDex.split("-");
800
+ const quote = rest.join("-").trim();
801
+ if (!base || !quote) return null;
802
+ return `${canonicalizeHyperliquidTokenCase(base)}/${canonicalizeHyperliquidTokenCase(quote)}`;
803
+ }
804
+ return null;
793
805
  }
794
- async function fetchHyperliquidOpenOrders(params) {
795
- const env = params.environment ?? "mainnet";
796
- return postInfo(env, { type: "openOrders", user: normalizeAddress(params.user) });
806
+ function resolveHyperliquidLeverageMode(symbol) {
807
+ return symbol.includes(":") ? "isolated" : "cross";
797
808
  }
798
- async function fetchHyperliquidFrontendOpenOrders(params) {
799
- const env = params.environment ?? "mainnet";
800
- return postInfo(env, {
801
- type: "frontendOpenOrders",
802
- user: normalizeAddress(params.user)
803
- });
809
+ function resolveHyperliquidProfileChain(environment) {
810
+ return environment === "testnet" ? "hyperliquid-testnet" : "hyperliquid";
804
811
  }
805
- async function fetchHyperliquidOrderStatus(params) {
806
- const env = params.environment ?? "mainnet";
807
- return postInfo(env, {
808
- type: "orderStatus",
809
- user: normalizeAddress(params.user),
810
- oid: params.oid
811
- });
812
+ function buildHyperliquidProfileAssets(params) {
813
+ const chain = resolveHyperliquidProfileChain(params.environment);
814
+ return params.assets.map((asset) => {
815
+ const symbols = asset.assetSymbols.map((symbol) => normalizeHyperliquidBaseSymbol(symbol)).filter((symbol) => Boolean(symbol));
816
+ if (symbols.length === 0) return null;
817
+ const explicitPair = typeof asset.pair === "string" ? resolveHyperliquidPair(asset.pair) : null;
818
+ const derivedPair = symbols.length === 1 ? resolveHyperliquidPair(asset.assetSymbols[0] ?? symbols[0]) : null;
819
+ const pair = explicitPair ?? derivedPair ?? void 0;
820
+ const leverage = typeof asset.leverage === "number" && Number.isFinite(asset.leverage) && asset.leverage > 0 ? asset.leverage : void 0;
821
+ const walletAddress = typeof asset.walletAddress === "string" && asset.walletAddress.trim().length > 0 ? asset.walletAddress.trim() : void 0;
822
+ return {
823
+ venue: "hyperliquid",
824
+ chain,
825
+ assetSymbols: symbols,
826
+ ...pair ? { pair } : {},
827
+ ...leverage ? { leverage } : {},
828
+ ...walletAddress ? { walletAddress } : {}
829
+ };
830
+ }).filter((asset) => asset !== null);
812
831
  }
813
- async function fetchHyperliquidHistoricalOrders(params) {
814
- const env = params.environment ?? "mainnet";
815
- return postInfo(env, {
816
- type: "historicalOrders",
817
- user: normalizeAddress(params.user)
818
- });
832
+ function parseSpotPairSymbol(symbol) {
833
+ const trimmed = symbol.trim();
834
+ if (!trimmed.includes("/")) return null;
835
+ const [rawBase, rawQuote] = trimmed.split("/");
836
+ const base = rawBase?.trim().toUpperCase() ?? "";
837
+ const quote = rawQuote?.trim().toUpperCase() ?? "";
838
+ if (!base || !quote) return null;
839
+ return { base, quote };
819
840
  }
820
- async function fetchHyperliquidUserFills(params) {
821
- const env = params.environment ?? "mainnet";
822
- return postInfo(env, {
823
- type: "userFills",
824
- user: normalizeAddress(params.user)
825
- });
841
+ function isHyperliquidSpotSymbol(symbol) {
842
+ const trimmed = symbol.trim();
843
+ if (!trimmed) return false;
844
+ if (trimmed.startsWith("@") || trimmed.includes("/")) return true;
845
+ if (trimmed.includes(":")) return false;
846
+ return resolveHyperliquidPair(trimmed) !== null;
826
847
  }
827
- async function fetchHyperliquidUserFillsByTime(params) {
828
- const env = params.environment ?? "mainnet";
829
- return postInfo(env, {
830
- type: "userFillsByTime",
831
- user: normalizeAddress(params.user),
832
- startTime: params.startTime,
833
- endTime: params.endTime
834
- });
848
+ function resolveHyperliquidMarketDataCoin(value) {
849
+ if (!value) return null;
850
+ const trimmed = value.trim();
851
+ if (!trimmed) return null;
852
+ if (trimmed.startsWith("@")) return trimmed;
853
+ const pair = resolveHyperliquidPair(trimmed);
854
+ if (pair && !extractHyperliquidDex(trimmed)) {
855
+ return pair;
856
+ }
857
+ return trimmed;
835
858
  }
836
- async function fetchHyperliquidUserRateLimit(params) {
837
- const env = params.environment ?? "mainnet";
838
- return postInfo(env, {
839
- type: "userRateLimit",
840
- user: normalizeAddress(params.user)
841
- });
859
+ function supportsHyperliquidBuilderFee(params) {
860
+ if (!isHyperliquidSpotSymbol(params.symbol)) {
861
+ return true;
862
+ }
863
+ return params.side === "sell";
842
864
  }
843
- async function fetchHyperliquidPreTransferCheck(params) {
844
- const env = params.environment ?? "mainnet";
845
- return postInfo(env, {
846
- type: "preTransferCheck",
847
- user: normalizeAddress(params.user),
848
- source: normalizeAddress(params.source)
849
- });
865
+ function resolveSpotMidCandidates(baseSymbol) {
866
+ const base = baseSymbol.trim().toUpperCase();
867
+ if (!base) return [];
868
+ const candidates = [base];
869
+ if (base.startsWith("U") && base.length > 1) {
870
+ candidates.push(base.slice(1));
871
+ }
872
+ return Array.from(new Set(candidates));
850
873
  }
851
- async function fetchHyperliquidSpotClearinghouseState(params) {
852
- const env = params.environment ?? "mainnet";
853
- return postInfo(env, {
854
- type: "spotClearinghouseState",
855
- user: normalizeAddress(params.user)
856
- });
874
+ function resolveSpotTokenCandidates(value) {
875
+ const normalized = normalizeSpotTokenName2(value).toUpperCase();
876
+ if (!normalized) return [];
877
+ const candidates = [normalized];
878
+ if (normalized.startsWith("U") && normalized.length > 1) {
879
+ candidates.push(normalized.slice(1));
880
+ }
881
+ return Array.from(new Set(candidates));
857
882
  }
858
-
859
- // src/adapters/hyperliquid/exchange.ts
860
- function resolveRequiredExchangeNonce(options) {
861
- if (typeof options.nonce === "number") {
862
- return options.nonce;
883
+ function resolveHyperliquidOrderSymbol(value) {
884
+ if (!value) return null;
885
+ const trimmed = value.trim();
886
+ if (!trimmed) return null;
887
+ if (trimmed.startsWith("@")) return trimmed;
888
+ if (trimmed.includes(":")) {
889
+ const [rawDex, ...restParts] = trimmed.split(":");
890
+ const dex = rawDex.trim().toLowerCase();
891
+ const rest = restParts.join(":");
892
+ const normalizedBase = normalizeHyperliquidBaseSymbol(rest);
893
+ if (!dex || !normalizedBase || normalizedBase === UNKNOWN_SYMBOL2) {
894
+ return null;
895
+ }
896
+ return `${dex}:${normalizedBase}`;
863
897
  }
864
- const resolved = options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.();
865
- if (resolved === void 0) {
866
- throw new Error(`${options.action} requires an explicit nonce or wallet nonce source.`);
898
+ const pair = resolveHyperliquidPair(trimmed);
899
+ if (pair) return pair;
900
+ return normalizeHyperliquidBaseSymbol(trimmed);
901
+ }
902
+ function resolveHyperliquidSymbol(asset, override) {
903
+ const raw = override && override.trim().length > 0 ? override.trim() : asset.trim();
904
+ if (!raw) return raw;
905
+ if (raw.startsWith("@")) return raw;
906
+ if (raw.includes(":")) {
907
+ const [dexRaw, ...restParts] = raw.split(":");
908
+ const dex = dexRaw.trim().toLowerCase();
909
+ const rest = restParts.join(":");
910
+ const normalizedBase = normalizeHyperliquidBaseSymbol(rest) ?? canonicalizeHyperliquidTokenCase(rest);
911
+ if (!dex) return normalizedBase;
912
+ return `${dex}:${normalizedBase}`;
867
913
  }
868
- return resolved;
914
+ if (raw.includes("/")) {
915
+ return resolveHyperliquidPair(raw) ?? raw;
916
+ }
917
+ if (raw.includes("-")) {
918
+ return resolveHyperliquidPair(raw) ?? raw;
919
+ }
920
+ return normalizeHyperliquidBaseSymbol(raw) ?? canonicalizeHyperliquidTokenCase(raw);
869
921
  }
870
- var HyperliquidExchangeClient = class {
871
- constructor(args) {
872
- this.wallet = args.wallet;
873
- this.environment = args.environment ?? "mainnet";
874
- this.vaultAddress = args.vaultAddress;
875
- this.expiresAfter = args.expiresAfter;
876
- const resolvedNonceSource = args.walletNonceProvider ?? args.wallet.nonceSource ?? args.nonceSource;
877
- if (!resolvedNonceSource) {
878
- throw new Error("Wallet nonce source is required for Hyperliquid exchange actions.");
922
+ function resolveHyperliquidPerpSymbol(asset) {
923
+ const raw = asset.trim();
924
+ if (!raw) return raw;
925
+ const dex = extractHyperliquidDex(raw);
926
+ const base = normalizeHyperliquidBaseSymbol(raw) ?? raw.toUpperCase();
927
+ return dex ? `${dex}:${base}` : base;
928
+ }
929
+ function resolveHyperliquidSpotSymbol(asset, defaultQuote = "USDC") {
930
+ const quote = defaultQuote.trim().toUpperCase() || "USDC";
931
+ const raw = asset.trim().toUpperCase();
932
+ if (!raw) {
933
+ return { symbol: raw, base: raw, quote };
934
+ }
935
+ const pair = resolveHyperliquidPair(raw);
936
+ if (pair) {
937
+ const [base2, pairQuote] = pair.split("/");
938
+ return {
939
+ symbol: pair,
940
+ base: base2?.trim() ?? raw,
941
+ quote: pairQuote?.trim() ?? quote
942
+ };
943
+ }
944
+ const base = normalizeHyperliquidBaseSymbol(raw) ?? raw;
945
+ return { symbol: `${base}/${quote}`, base, quote };
946
+ }
947
+
948
+ // src/adapters/hyperliquid/info.ts
949
+ var HYPERLIQUID_HIP3_DEXES = [
950
+ "xyz",
951
+ "flx",
952
+ "vntl",
953
+ "hyna",
954
+ "km",
955
+ "cash"
956
+ ];
957
+ async function postInfo(environment, payload) {
958
+ const baseUrl = API_BASES[environment];
959
+ const response = await fetch(`${baseUrl}/info`, {
960
+ method: "POST",
961
+ headers: { "content-type": "application/json" },
962
+ body: JSON.stringify(payload)
963
+ });
964
+ const data = await response.json().catch(() => null);
965
+ if (!response.ok) {
966
+ throw new HyperliquidApiError(
967
+ "Hyperliquid info request failed.",
968
+ data ?? { status: response.status }
969
+ );
970
+ }
971
+ return data;
972
+ }
973
+ function mergeHyperliquidOpenOrders(batches) {
974
+ const merged = /* @__PURE__ */ new Map();
975
+ for (const batch of batches) {
976
+ for (const order of batch) {
977
+ const oid = typeof order.oid === "number" || typeof order.oid === "string" ? String(order.oid) : "no-oid";
978
+ const cloid = typeof order.cloid === "string" && order.cloid.trim().length > 0 ? order.cloid : "no-cloid";
979
+ merged.set(`${oid}:${cloid}`, order);
879
980
  }
880
- this.nonceSource = resolvedNonceSource;
881
981
  }
882
- cancel(cancels) {
883
- return cancelHyperliquidOrders({
884
- wallet: this.wallet,
885
- cancels,
886
- environment: this.environment,
887
- vaultAddress: this.vaultAddress,
888
- expiresAfter: this.expiresAfter,
889
- nonceSource: this.nonceSource
890
- });
982
+ return [...merged.values()];
983
+ }
984
+ function readNumber(value) {
985
+ if (typeof value === "number") {
986
+ return Number.isFinite(value) ? value : null;
891
987
  }
892
- cancelByCloid(cancels) {
893
- return cancelHyperliquidOrdersByCloid({
894
- wallet: this.wallet,
895
- cancels,
896
- environment: this.environment,
897
- vaultAddress: this.vaultAddress,
898
- expiresAfter: this.expiresAfter,
899
- nonceSource: this.nonceSource
900
- });
988
+ if (typeof value === "string" && value.trim().length > 0) {
989
+ const parsed = Number.parseFloat(value);
990
+ return Number.isFinite(parsed) ? parsed : null;
901
991
  }
902
- cancelAll() {
903
- return cancelAllHyperliquidOrders({
904
- wallet: this.wallet,
905
- environment: this.environment,
906
- vaultAddress: this.vaultAddress,
907
- expiresAfter: this.expiresAfter,
908
- nonceSource: this.nonceSource
909
- });
992
+ return null;
993
+ }
994
+ var HyperliquidInfoClient = class {
995
+ constructor(environment = "mainnet") {
996
+ this.environment = environment;
910
997
  }
911
- scheduleCancel(time) {
912
- return scheduleHyperliquidCancel({
913
- wallet: this.wallet,
914
- time,
915
- environment: this.environment,
916
- vaultAddress: this.vaultAddress,
917
- expiresAfter: this.expiresAfter,
918
- nonceSource: this.nonceSource
919
- });
998
+ meta() {
999
+ return fetchHyperliquidMeta(this.environment);
920
1000
  }
921
- modify(modification) {
922
- return modifyHyperliquidOrder({
923
- wallet: this.wallet,
924
- modification,
925
- environment: this.environment,
926
- vaultAddress: this.vaultAddress,
927
- expiresAfter: this.expiresAfter,
928
- nonceSource: this.nonceSource
929
- });
1001
+ metaAndAssetCtxs() {
1002
+ return fetchHyperliquidMetaAndAssetCtxs(this.environment);
930
1003
  }
931
- batchModify(modifications) {
932
- return batchModifyHyperliquidOrders({
933
- wallet: this.wallet,
934
- modifications,
935
- environment: this.environment,
936
- vaultAddress: this.vaultAddress,
937
- expiresAfter: this.expiresAfter,
938
- nonceSource: this.nonceSource
939
- });
1004
+ spotMeta() {
1005
+ return fetchHyperliquidSpotMeta(this.environment);
940
1006
  }
941
- twapOrder(twap) {
942
- return placeHyperliquidTwapOrder({
943
- wallet: this.wallet,
944
- twap,
945
- environment: this.environment,
946
- vaultAddress: this.vaultAddress,
947
- expiresAfter: this.expiresAfter,
948
- nonceSource: this.nonceSource
949
- });
1007
+ spotMetaAndAssetCtxs() {
1008
+ return fetchHyperliquidSpotMetaAndAssetCtxs(this.environment);
950
1009
  }
951
- twapCancel(cancel) {
1010
+ assetCtxs() {
1011
+ return fetchHyperliquidAssetCtxs(this.environment);
1012
+ }
1013
+ spotAssetCtxs() {
1014
+ return fetchHyperliquidSpotAssetCtxs(this.environment);
1015
+ }
1016
+ openOrders(user) {
1017
+ return fetchHyperliquidOpenOrders({ user, environment: this.environment });
1018
+ }
1019
+ frontendOpenOrders(user) {
1020
+ return fetchHyperliquidFrontendOpenOrders({
1021
+ user,
1022
+ environment: this.environment
1023
+ });
1024
+ }
1025
+ orderStatus(user, oid) {
1026
+ return fetchHyperliquidOrderStatus({
1027
+ user,
1028
+ oid,
1029
+ environment: this.environment
1030
+ });
1031
+ }
1032
+ historicalOrders(user) {
1033
+ return fetchHyperliquidHistoricalOrders({
1034
+ user,
1035
+ environment: this.environment
1036
+ });
1037
+ }
1038
+ userFills(user) {
1039
+ return fetchHyperliquidUserFills({ user, environment: this.environment });
1040
+ }
1041
+ userFillsByTime(user, startTime, endTime) {
1042
+ return fetchHyperliquidUserFillsByTime({
1043
+ user,
1044
+ startTime,
1045
+ endTime,
1046
+ environment: this.environment
1047
+ });
1048
+ }
1049
+ userRateLimit(user) {
1050
+ return fetchHyperliquidUserRateLimit({
1051
+ user,
1052
+ environment: this.environment
1053
+ });
1054
+ }
1055
+ preTransferCheck(user, source) {
1056
+ return fetchHyperliquidPreTransferCheck({
1057
+ user,
1058
+ source,
1059
+ environment: this.environment
1060
+ });
1061
+ }
1062
+ spotClearinghouseState(user) {
1063
+ return fetchHyperliquidSpotClearinghouseState({
1064
+ user,
1065
+ environment: this.environment
1066
+ });
1067
+ }
1068
+ activeAsset(user, symbol) {
1069
+ return fetchHyperliquidActiveAsset({
1070
+ user,
1071
+ symbol,
1072
+ environment: this.environment
1073
+ });
1074
+ }
1075
+ };
1076
+ async function fetchHyperliquidMeta(environment = "mainnet") {
1077
+ return postInfo(environment, { type: "meta" });
1078
+ }
1079
+ async function fetchHyperliquidMetaAndAssetCtxs(environment = "mainnet") {
1080
+ return postInfo(environment, { type: "metaAndAssetCtxs" });
1081
+ }
1082
+ async function fetchHyperliquidSpotMeta(environment = "mainnet") {
1083
+ return postInfo(environment, { type: "spotMeta" });
1084
+ }
1085
+ async function fetchHyperliquidSpotMetaAndAssetCtxs(environment = "mainnet") {
1086
+ return postInfo(environment, { type: "spotMetaAndAssetCtxs" });
1087
+ }
1088
+ async function fetchHyperliquidAssetCtxs(environment = "mainnet") {
1089
+ return postInfo(environment, { type: "assetCtxs" });
1090
+ }
1091
+ async function fetchHyperliquidSpotAssetCtxs(environment = "mainnet") {
1092
+ return postInfo(environment, { type: "spotAssetCtxs" });
1093
+ }
1094
+ async function fetchHyperliquidOpenOrders(params) {
1095
+ const env = params.environment ?? "mainnet";
1096
+ return postInfo(env, {
1097
+ type: "openOrders",
1098
+ user: normalizeAddress(params.user),
1099
+ ...params.dex ? { dex: params.dex.trim().toLowerCase() } : {}
1100
+ });
1101
+ }
1102
+ async function fetchHyperliquidFrontendOpenOrders(params) {
1103
+ const env = params.environment ?? "mainnet";
1104
+ return postInfo(env, {
1105
+ type: "frontendOpenOrders",
1106
+ user: normalizeAddress(params.user),
1107
+ ...params.dex ? { dex: params.dex.trim().toLowerCase() } : {}
1108
+ });
1109
+ }
1110
+ async function fetchHyperliquidOrderStatus(params) {
1111
+ const env = params.environment ?? "mainnet";
1112
+ return postInfo(env, {
1113
+ type: "orderStatus",
1114
+ user: normalizeAddress(params.user),
1115
+ oid: params.oid
1116
+ });
1117
+ }
1118
+ async function fetchHyperliquidHistoricalOrders(params) {
1119
+ const env = params.environment ?? "mainnet";
1120
+ return postInfo(env, {
1121
+ type: "historicalOrders",
1122
+ user: normalizeAddress(params.user),
1123
+ ...params.dex ? { dex: params.dex.trim().toLowerCase() } : {}
1124
+ });
1125
+ }
1126
+ async function fetchHyperliquidUserFills(params) {
1127
+ const env = params.environment ?? "mainnet";
1128
+ return postInfo(env, {
1129
+ type: "userFills",
1130
+ user: normalizeAddress(params.user)
1131
+ });
1132
+ }
1133
+ async function fetchHyperliquidUserFillsByTime(params) {
1134
+ const env = params.environment ?? "mainnet";
1135
+ return postInfo(env, {
1136
+ type: "userFillsByTime",
1137
+ user: normalizeAddress(params.user),
1138
+ startTime: params.startTime,
1139
+ endTime: params.endTime
1140
+ });
1141
+ }
1142
+ async function fetchHyperliquidUserRateLimit(params) {
1143
+ const env = params.environment ?? "mainnet";
1144
+ return postInfo(env, {
1145
+ type: "userRateLimit",
1146
+ user: normalizeAddress(params.user)
1147
+ });
1148
+ }
1149
+ async function fetchHyperliquidPreTransferCheck(params) {
1150
+ const env = params.environment ?? "mainnet";
1151
+ return postInfo(env, {
1152
+ type: "preTransferCheck",
1153
+ user: normalizeAddress(params.user),
1154
+ source: normalizeAddress(params.source)
1155
+ });
1156
+ }
1157
+ async function fetchHyperliquidSpotClearinghouseState(params) {
1158
+ const env = params.environment ?? "mainnet";
1159
+ return postInfo(env, {
1160
+ type: "spotClearinghouseState",
1161
+ user: normalizeAddress(params.user)
1162
+ });
1163
+ }
1164
+ function getKnownHyperliquidDexes(environment = "mainnet") {
1165
+ return environment === "mainnet" ? [...HYPERLIQUID_HIP3_DEXES] : [];
1166
+ }
1167
+ async function fetchHyperliquidOpenOrdersAcrossDexes(params) {
1168
+ const environment = params.environment ?? "mainnet";
1169
+ const requests = [
1170
+ ...params.includePrimary === false ? [] : [fetchHyperliquidOpenOrders({ environment, user: params.user })],
1171
+ ...getKnownHyperliquidDexes(environment).filter((dex) => !(params.dexes && !params.dexes.includes(dex))).map(
1172
+ (dex) => fetchHyperliquidOpenOrders({
1173
+ environment,
1174
+ user: params.user,
1175
+ dex
1176
+ })
1177
+ )
1178
+ ];
1179
+ const batches = await Promise.all(requests);
1180
+ return mergeHyperliquidOpenOrders(batches);
1181
+ }
1182
+ async function fetchHyperliquidFrontendOpenOrdersAcrossDexes(params) {
1183
+ const environment = params.environment ?? "mainnet";
1184
+ const requests = [
1185
+ ...params.includePrimary === false ? [] : [fetchHyperliquidFrontendOpenOrders({ environment, user: params.user })],
1186
+ ...getKnownHyperliquidDexes(environment).filter((dex) => !(params.dexes && !params.dexes.includes(dex))).map(
1187
+ (dex) => fetchHyperliquidFrontendOpenOrders({
1188
+ environment,
1189
+ user: params.user,
1190
+ dex
1191
+ })
1192
+ )
1193
+ ];
1194
+ const batches = await Promise.all(requests);
1195
+ return mergeHyperliquidOpenOrders(batches);
1196
+ }
1197
+ async function fetchHyperliquidActiveAsset(params) {
1198
+ const environment = params.environment ?? "mainnet";
1199
+ const coin = resolveHyperliquidOrderSymbol(params.symbol);
1200
+ if (!coin) {
1201
+ throw new Error(`Unable to resolve Hyperliquid active asset symbol: ${params.symbol}`);
1202
+ }
1203
+ const raw = await postInfo(environment, {
1204
+ type: "activeAssetData",
1205
+ user: normalizeAddress(params.user),
1206
+ coin
1207
+ });
1208
+ const record = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
1209
+ const leverageRecord = record?.leverage && typeof record.leverage === "object" && !Array.isArray(record.leverage) ? record.leverage : null;
1210
+ return {
1211
+ coin,
1212
+ leverage: leverageRecord && "value" in leverageRecord ? readNumber(leverageRecord.value) : readNumber(record?.leverage),
1213
+ leverageType: leverageRecord && typeof leverageRecord.type === "string" ? leverageRecord.type : null,
1214
+ raw
1215
+ };
1216
+ }
1217
+
1218
+ // src/adapters/hyperliquid/exchange.ts
1219
+ function resolveRequiredExchangeNonce(options) {
1220
+ if (typeof options.nonce === "number") {
1221
+ return options.nonce;
1222
+ }
1223
+ const resolved = options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.();
1224
+ if (resolved === void 0) {
1225
+ throw new Error(`${options.action} requires an explicit nonce or wallet nonce source.`);
1226
+ }
1227
+ return resolved;
1228
+ }
1229
+ var HyperliquidExchangeClient = class {
1230
+ constructor(args) {
1231
+ this.wallet = args.wallet;
1232
+ this.environment = args.environment ?? "mainnet";
1233
+ this.vaultAddress = args.vaultAddress;
1234
+ this.expiresAfter = args.expiresAfter;
1235
+ const resolvedNonceSource = args.walletNonceProvider ?? args.wallet.nonceSource ?? args.nonceSource;
1236
+ if (!resolvedNonceSource) {
1237
+ throw new Error("Wallet nonce source is required for Hyperliquid exchange actions.");
1238
+ }
1239
+ this.nonceSource = resolvedNonceSource;
1240
+ }
1241
+ cancel(cancels) {
1242
+ return cancelHyperliquidOrders({
1243
+ wallet: this.wallet,
1244
+ cancels,
1245
+ environment: this.environment,
1246
+ vaultAddress: this.vaultAddress,
1247
+ expiresAfter: this.expiresAfter,
1248
+ nonceSource: this.nonceSource
1249
+ });
1250
+ }
1251
+ cancelByCloid(cancels) {
1252
+ return cancelHyperliquidOrdersByCloid({
1253
+ wallet: this.wallet,
1254
+ cancels,
1255
+ environment: this.environment,
1256
+ vaultAddress: this.vaultAddress,
1257
+ expiresAfter: this.expiresAfter,
1258
+ nonceSource: this.nonceSource
1259
+ });
1260
+ }
1261
+ cancelAll() {
1262
+ return cancelAllHyperliquidOrders({
1263
+ wallet: this.wallet,
1264
+ environment: this.environment,
1265
+ vaultAddress: this.vaultAddress,
1266
+ expiresAfter: this.expiresAfter,
1267
+ nonceSource: this.nonceSource
1268
+ });
1269
+ }
1270
+ scheduleCancel(time) {
1271
+ return scheduleHyperliquidCancel({
1272
+ wallet: this.wallet,
1273
+ time,
1274
+ environment: this.environment,
1275
+ vaultAddress: this.vaultAddress,
1276
+ expiresAfter: this.expiresAfter,
1277
+ nonceSource: this.nonceSource
1278
+ });
1279
+ }
1280
+ modify(modification) {
1281
+ return modifyHyperliquidOrder({
1282
+ wallet: this.wallet,
1283
+ modification,
1284
+ environment: this.environment,
1285
+ vaultAddress: this.vaultAddress,
1286
+ expiresAfter: this.expiresAfter,
1287
+ nonceSource: this.nonceSource
1288
+ });
1289
+ }
1290
+ batchModify(modifications) {
1291
+ return batchModifyHyperliquidOrders({
1292
+ wallet: this.wallet,
1293
+ modifications,
1294
+ environment: this.environment,
1295
+ vaultAddress: this.vaultAddress,
1296
+ expiresAfter: this.expiresAfter,
1297
+ nonceSource: this.nonceSource
1298
+ });
1299
+ }
1300
+ twapOrder(twap) {
1301
+ return placeHyperliquidTwapOrder({
1302
+ wallet: this.wallet,
1303
+ twap,
1304
+ environment: this.environment,
1305
+ vaultAddress: this.vaultAddress,
1306
+ expiresAfter: this.expiresAfter,
1307
+ nonceSource: this.nonceSource
1308
+ });
1309
+ }
1310
+ twapCancel(cancel) {
952
1311
  return cancelHyperliquidTwapOrder({
953
1312
  wallet: this.wallet,
954
1313
  cancel,
@@ -1335,429 +1694,163 @@ async function submitExchangeAction(options, action) {
1335
1694
  }
1336
1695
  async function withAssetIndexes(options, entries, mapper) {
1337
1696
  const env = options.environment ?? "mainnet";
1338
- return Promise.all(
1339
- entries.map(async (entry) => {
1340
- const assetIndex = await resolveHyperliquidAssetIndex({
1341
- symbol: entry.symbol,
1342
- baseUrl: API_BASES[env],
1343
- environment: env,
1344
- fetcher: (...args) => fetch(...args)
1345
- });
1346
- return mapper(assetIndex, entry);
1347
- })
1348
- );
1349
- }
1350
- async function buildOrder(intent, options) {
1351
- assertSymbol(intent.symbol);
1352
- assertPositiveDecimal(intent.price, "price");
1353
- assertPositiveDecimal(intent.size, "size");
1354
- const env = options.environment ?? "mainnet";
1355
- const assetIndex = await resolveHyperliquidAssetIndex({
1356
- symbol: intent.symbol,
1357
- baseUrl: API_BASES[env],
1358
- environment: env,
1359
- fetcher: (...args) => fetch(...args)
1360
- });
1361
- const limitOrTrigger = intent.trigger ? mapTrigger(intent.trigger) : {
1362
- limit: {
1363
- tif: intent.tif ?? "Ioc"
1364
- }
1365
- };
1366
- return {
1367
- a: assetIndex,
1368
- b: intent.side === "buy",
1369
- p: toApiDecimal(intent.price),
1370
- s: toApiDecimal(intent.size),
1371
- r: intent.reduceOnly ?? false,
1372
- t: limitOrTrigger,
1373
- ...intent.clientId ? {
1374
- c: normalizeCloid(intent.clientId)
1375
- } : {}
1376
- };
1377
- }
1378
- function mapTrigger(trigger) {
1379
- assertPositiveDecimal(trigger.triggerPx, "triggerPx");
1380
- return {
1381
- trigger: {
1382
- isMarket: Boolean(trigger.isMarket),
1383
- triggerPx: toApiDecimal(trigger.triggerPx),
1384
- tpsl: trigger.tpsl
1385
- }
1386
- };
1387
- }
1388
- function assertSymbol(value) {
1389
- assertString(value, "symbol");
1390
- }
1391
- function normalizeUsdToInt(value) {
1392
- if (typeof value === "bigint") {
1393
- if (value < 0n) {
1394
- throw new Error("usd must be non-negative.");
1395
- }
1396
- return Number(value);
1397
- }
1398
- const parsed = typeof value === "string" ? Number.parseFloat(value) : Number(value);
1399
- if (!Number.isFinite(parsed) || parsed < 0) {
1400
- throw new Error("usd must be a non-negative number.");
1401
- }
1402
- return Math.round(parsed * 1e6);
1403
- }
1404
- function assertString(value, label) {
1405
- if (typeof value !== "string" || !value.trim()) {
1406
- throw new Error(`${label} must be a non-empty string.`);
1407
- }
1408
- }
1409
- function assertPositiveDecimal(value, label) {
1410
- if (typeof value === "number") {
1411
- assertPositiveNumber(value, label);
1412
- return;
1413
- }
1414
- if (typeof value === "bigint") {
1415
- if (value <= 0n) {
1416
- throw new Error(`${label} must be positive.`);
1417
- }
1418
- return;
1419
- }
1420
- assertString(value, label);
1421
- if (!/^(?:\d+\.?\d*|\.\d+)$/.test(value.trim())) {
1422
- throw new Error(`${label} must be a positive decimal string.`);
1423
- }
1424
- const numeric = Number(value);
1425
- if (!Number.isFinite(numeric) || numeric <= 0) {
1426
- throw new Error(`${label} must be positive.`);
1427
- }
1428
- }
1429
- function collectExchangeErrorMessages(payload) {
1430
- if (!payload || typeof payload !== "object") return [];
1431
- const root = payload;
1432
- const messages = [];
1433
- const statuses = root.response?.data?.statuses;
1434
- if (Array.isArray(statuses)) {
1435
- statuses.forEach((status, index) => {
1436
- if (status && typeof status === "object" && "error" in status && typeof status.error === "string") {
1437
- const errorText = status.error;
1438
- messages.push(`status[${index}]: ${errorText}`);
1439
- }
1440
- });
1441
- }
1442
- const singleStatus = root.response?.data?.status;
1443
- if (singleStatus && typeof singleStatus === "object" && "error" in singleStatus && typeof singleStatus.error === "string") {
1444
- messages.push(singleStatus.error);
1445
- }
1446
- return messages;
1447
- }
1448
- async function postExchange(env, body) {
1449
- const response = await fetch(`${API_BASES[env]}/exchange`, {
1450
- method: "POST",
1451
- headers: { "content-type": "application/json" },
1452
- body: JSON.stringify(body)
1453
- });
1454
- const text = await response.text().catch(() => "");
1455
- const json = (() => {
1456
- if (!text) return null;
1457
- try {
1458
- return JSON.parse(text);
1459
- } catch {
1460
- return null;
1461
- }
1462
- })();
1463
- if (!response.ok) {
1464
- throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
1465
- status: response.status,
1466
- statusText: response.statusText,
1467
- body: json ?? (text ? text : null)
1468
- });
1469
- }
1470
- if (!json) {
1471
- throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
1472
- status: response.status,
1473
- statusText: response.statusText,
1474
- body: text ? text : null
1475
- });
1476
- }
1477
- if (json.status !== "ok") {
1478
- throw new HyperliquidApiError("Hyperliquid exchange returned error.", {
1479
- status: response.status,
1480
- statusText: response.statusText,
1481
- body: json
1482
- });
1483
- }
1484
- const nestedErrors = collectExchangeErrorMessages(json);
1485
- if (nestedErrors.length > 0) {
1486
- throw new HyperliquidApiError("Hyperliquid exchange returned action errors.", {
1487
- status: response.status,
1488
- statusText: response.statusText,
1489
- body: json,
1490
- errors: nestedErrors
1491
- });
1492
- }
1493
- return json;
1494
- }
1495
-
1496
- // src/adapters/hyperliquid/symbols.ts
1497
- var UNKNOWN_SYMBOL2 = "UNKNOWN";
1498
- function extractHyperliquidDex(symbol) {
1499
- const idx = symbol.indexOf(":");
1500
- if (idx <= 0) return null;
1501
- const dex = symbol.slice(0, idx).trim().toLowerCase();
1502
- return dex || null;
1503
- }
1504
- function parseHyperliquidSymbol(value) {
1505
- if (!value) return null;
1506
- const trimmed = value.trim();
1507
- if (!trimmed) return null;
1508
- if (trimmed.startsWith("@")) {
1509
- return {
1510
- raw: trimmed,
1511
- kind: "spotIndex",
1512
- normalized: trimmed,
1513
- routeTicker: trimmed,
1514
- displaySymbol: trimmed,
1515
- base: null,
1516
- quote: null,
1517
- pair: null,
1518
- dex: null,
1519
- leverageMode: "cross"
1520
- };
1521
- }
1522
- const dex = extractHyperliquidDex(trimmed);
1523
- const pair = resolveHyperliquidPair(trimmed);
1524
- const base = normalizeHyperliquidBaseSymbol(trimmed);
1525
- if (dex) {
1526
- if (!base) return null;
1527
- return {
1528
- raw: trimmed,
1529
- kind: "perp",
1530
- normalized: `${dex}:${base}`,
1531
- routeTicker: `${dex}:${base}`,
1532
- displaySymbol: `${dex.toUpperCase()}:${base}-USDC`,
1533
- base,
1534
- quote: null,
1535
- pair: null,
1536
- dex,
1537
- leverageMode: "isolated"
1538
- };
1539
- }
1540
- if (pair) {
1541
- const [pairBase, pairQuote] = pair.split("/");
1542
- return {
1543
- raw: trimmed,
1544
- kind: "spot",
1545
- normalized: pair,
1546
- routeTicker: pair.replace("/", "-"),
1547
- displaySymbol: pair.replace("/", "-"),
1548
- base: pairBase ?? null,
1549
- quote: pairQuote ?? null,
1550
- pair,
1551
- dex: null,
1552
- leverageMode: "cross"
1553
- };
1554
- }
1555
- if (!base) return null;
1556
- return {
1557
- raw: trimmed,
1558
- kind: "perp",
1559
- normalized: base,
1560
- routeTicker: base,
1561
- displaySymbol: `${base}-USDC`,
1562
- base,
1563
- quote: null,
1564
- pair: null,
1565
- dex: null,
1566
- leverageMode: "cross"
1567
- };
1568
- }
1569
- function normalizeSpotTokenName2(value) {
1570
- const raw = (value ?? "").trim();
1571
- if (!raw) return "";
1572
- if (raw.endsWith("0") && raw.length > 1) {
1573
- return raw.slice(0, -1);
1574
- }
1575
- return raw;
1576
- }
1577
- function canonicalizeHyperliquidTokenCase(value) {
1578
- const trimmed = value.trim();
1579
- if (!trimmed) return "";
1580
- return trimmed === trimmed.toLowerCase() ? trimmed.toUpperCase() : trimmed;
1581
- }
1582
- function normalizeHyperliquidBaseSymbol(value) {
1583
- if (!value) return null;
1584
- const trimmed = value.trim();
1585
- if (!trimmed) return null;
1586
- const withoutDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
1587
- const base = withoutDex.split("-")[0] ?? withoutDex;
1588
- const baseNoPair = base.split("/")[0] ?? base;
1589
- const normalized = canonicalizeHyperliquidTokenCase(baseNoPair);
1590
- if (!normalized || normalized === UNKNOWN_SYMBOL2) return null;
1591
- return normalized;
1592
- }
1593
- function normalizeHyperliquidMetaSymbol(symbol) {
1594
- const trimmed = symbol.trim();
1595
- const noDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
1596
- const noPair = noDex.split("-")[0] ?? noDex;
1597
- return (noPair.split("/")[0] ?? noPair).trim();
1598
- }
1599
- function resolveHyperliquidPair(value) {
1600
- if (!value) return null;
1601
- const trimmed = value.trim();
1602
- if (!trimmed) return null;
1603
- const withoutDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
1604
- if (withoutDex.includes("/")) {
1605
- const [base, ...rest] = withoutDex.split("/");
1606
- const quote = rest.join("/").trim();
1607
- if (!base || !quote) return null;
1608
- return `${canonicalizeHyperliquidTokenCase(base)}/${canonicalizeHyperliquidTokenCase(quote)}`;
1609
- }
1610
- if (withoutDex.includes("-")) {
1611
- const [base, ...rest] = withoutDex.split("-");
1612
- const quote = rest.join("-").trim();
1613
- if (!base || !quote) return null;
1614
- return `${canonicalizeHyperliquidTokenCase(base)}/${canonicalizeHyperliquidTokenCase(quote)}`;
1615
- }
1616
- return null;
1617
- }
1618
- function resolveHyperliquidLeverageMode(symbol) {
1619
- return symbol.includes(":") ? "isolated" : "cross";
1620
- }
1621
- function resolveHyperliquidProfileChain(environment) {
1622
- return environment === "testnet" ? "hyperliquid-testnet" : "hyperliquid";
1697
+ return Promise.all(
1698
+ entries.map(async (entry) => {
1699
+ const assetIndex = await resolveHyperliquidAssetIndex({
1700
+ symbol: entry.symbol,
1701
+ baseUrl: API_BASES[env],
1702
+ environment: env,
1703
+ fetcher: (...args) => fetch(...args)
1704
+ });
1705
+ return mapper(assetIndex, entry);
1706
+ })
1707
+ );
1623
1708
  }
1624
- function buildHyperliquidProfileAssets(params) {
1625
- const chain = resolveHyperliquidProfileChain(params.environment);
1626
- return params.assets.map((asset) => {
1627
- const symbols = asset.assetSymbols.map((symbol) => normalizeHyperliquidBaseSymbol(symbol)).filter((symbol) => Boolean(symbol));
1628
- if (symbols.length === 0) return null;
1629
- const explicitPair = typeof asset.pair === "string" ? resolveHyperliquidPair(asset.pair) : null;
1630
- const derivedPair = symbols.length === 1 ? resolveHyperliquidPair(asset.assetSymbols[0] ?? symbols[0]) : null;
1631
- const pair = explicitPair ?? derivedPair ?? void 0;
1632
- const leverage = typeof asset.leverage === "number" && Number.isFinite(asset.leverage) && asset.leverage > 0 ? asset.leverage : void 0;
1633
- const walletAddress = typeof asset.walletAddress === "string" && asset.walletAddress.trim().length > 0 ? asset.walletAddress.trim() : void 0;
1634
- return {
1635
- venue: "hyperliquid",
1636
- chain,
1637
- assetSymbols: symbols,
1638
- ...pair ? { pair } : {},
1639
- ...leverage ? { leverage } : {},
1640
- ...walletAddress ? { walletAddress } : {}
1641
- };
1642
- }).filter((asset) => asset !== null);
1709
+ async function buildOrder(intent, options) {
1710
+ assertSymbol(intent.symbol);
1711
+ assertPositiveDecimal(intent.price, "price");
1712
+ assertPositiveDecimal(intent.size, "size");
1713
+ const env = options.environment ?? "mainnet";
1714
+ const assetIndex = await resolveHyperliquidAssetIndex({
1715
+ symbol: intent.symbol,
1716
+ baseUrl: API_BASES[env],
1717
+ environment: env,
1718
+ fetcher: (...args) => fetch(...args)
1719
+ });
1720
+ const limitOrTrigger = intent.trigger ? mapTrigger(intent.trigger) : {
1721
+ limit: {
1722
+ tif: intent.tif ?? "Ioc"
1723
+ }
1724
+ };
1725
+ return {
1726
+ a: assetIndex,
1727
+ b: intent.side === "buy",
1728
+ p: toApiDecimal(intent.price),
1729
+ s: toApiDecimal(intent.size),
1730
+ r: intent.reduceOnly ?? false,
1731
+ t: limitOrTrigger,
1732
+ ...intent.clientId ? {
1733
+ c: normalizeCloid(intent.clientId)
1734
+ } : {}
1735
+ };
1643
1736
  }
1644
- function parseSpotPairSymbol(symbol) {
1645
- const trimmed = symbol.trim();
1646
- if (!trimmed.includes("/")) return null;
1647
- const [rawBase, rawQuote] = trimmed.split("/");
1648
- const base = rawBase?.trim().toUpperCase() ?? "";
1649
- const quote = rawQuote?.trim().toUpperCase() ?? "";
1650
- if (!base || !quote) return null;
1651
- return { base, quote };
1737
+ function mapTrigger(trigger) {
1738
+ assertPositiveDecimal(trigger.triggerPx, "triggerPx");
1739
+ return {
1740
+ trigger: {
1741
+ isMarket: Boolean(trigger.isMarket),
1742
+ triggerPx: toApiDecimal(trigger.triggerPx),
1743
+ tpsl: trigger.tpsl
1744
+ }
1745
+ };
1652
1746
  }
1653
- function isHyperliquidSpotSymbol(symbol) {
1654
- const trimmed = symbol.trim();
1655
- if (!trimmed) return false;
1656
- if (trimmed.startsWith("@") || trimmed.includes("/")) return true;
1657
- if (trimmed.includes(":")) return false;
1658
- return resolveHyperliquidPair(trimmed) !== null;
1747
+ function assertSymbol(value) {
1748
+ assertString(value, "symbol");
1659
1749
  }
1660
- function resolveHyperliquidMarketDataCoin(value) {
1661
- if (!value) return null;
1662
- const trimmed = value.trim();
1663
- if (!trimmed) return null;
1664
- if (trimmed.startsWith("@")) return trimmed;
1665
- const pair = resolveHyperliquidPair(trimmed);
1666
- if (pair && !extractHyperliquidDex(trimmed)) {
1667
- return pair;
1750
+ function normalizeUsdToInt(value) {
1751
+ if (typeof value === "bigint") {
1752
+ if (value < 0n) {
1753
+ throw new Error("usd must be non-negative.");
1754
+ }
1755
+ return Number(value);
1668
1756
  }
1669
- return trimmed;
1670
- }
1671
- function supportsHyperliquidBuilderFee(params) {
1672
- if (!isHyperliquidSpotSymbol(params.symbol)) {
1673
- return true;
1757
+ const parsed = typeof value === "string" ? Number.parseFloat(value) : Number(value);
1758
+ if (!Number.isFinite(parsed) || parsed < 0) {
1759
+ throw new Error("usd must be a non-negative number.");
1674
1760
  }
1675
- return params.side === "sell";
1761
+ return Math.round(parsed * 1e6);
1676
1762
  }
1677
- function resolveSpotMidCandidates(baseSymbol) {
1678
- const base = baseSymbol.trim().toUpperCase();
1679
- if (!base) return [];
1680
- const candidates = [base];
1681
- if (base.startsWith("U") && base.length > 1) {
1682
- candidates.push(base.slice(1));
1763
+ function assertString(value, label) {
1764
+ if (typeof value !== "string" || !value.trim()) {
1765
+ throw new Error(`${label} must be a non-empty string.`);
1683
1766
  }
1684
- return Array.from(new Set(candidates));
1685
1767
  }
1686
- function resolveSpotTokenCandidates(value) {
1687
- const normalized = normalizeSpotTokenName2(value).toUpperCase();
1688
- if (!normalized) return [];
1689
- const candidates = [normalized];
1690
- if (normalized.startsWith("U") && normalized.length > 1) {
1691
- candidates.push(normalized.slice(1));
1768
+ function assertPositiveDecimal(value, label) {
1769
+ if (typeof value === "number") {
1770
+ assertPositiveNumber(value, label);
1771
+ return;
1692
1772
  }
1693
- return Array.from(new Set(candidates));
1694
- }
1695
- function resolveHyperliquidOrderSymbol(value) {
1696
- if (!value) return null;
1697
- const trimmed = value.trim();
1698
- if (!trimmed) return null;
1699
- if (trimmed.startsWith("@")) return trimmed;
1700
- if (trimmed.includes(":")) {
1701
- const [rawDex, ...restParts] = trimmed.split(":");
1702
- const dex = rawDex.trim().toLowerCase();
1703
- const rest = restParts.join(":");
1704
- const normalizedBase = normalizeHyperliquidBaseSymbol(rest);
1705
- if (!dex || !normalizedBase || normalizedBase === UNKNOWN_SYMBOL2) {
1706
- return null;
1773
+ if (typeof value === "bigint") {
1774
+ if (value <= 0n) {
1775
+ throw new Error(`${label} must be positive.`);
1707
1776
  }
1708
- return `${dex}:${normalizedBase}`;
1709
- }
1710
- const pair = resolveHyperliquidPair(trimmed);
1711
- if (pair) return pair;
1712
- return normalizeHyperliquidBaseSymbol(trimmed);
1713
- }
1714
- function resolveHyperliquidSymbol(asset, override) {
1715
- const raw = override && override.trim().length > 0 ? override.trim() : asset.trim();
1716
- if (!raw) return raw;
1717
- if (raw.startsWith("@")) return raw;
1718
- if (raw.includes(":")) {
1719
- const [dexRaw, ...restParts] = raw.split(":");
1720
- const dex = dexRaw.trim().toLowerCase();
1721
- const rest = restParts.join(":");
1722
- const normalizedBase = normalizeHyperliquidBaseSymbol(rest) ?? canonicalizeHyperliquidTokenCase(rest);
1723
- if (!dex) return normalizedBase;
1724
- return `${dex}:${normalizedBase}`;
1777
+ return;
1725
1778
  }
1726
- if (raw.includes("/")) {
1727
- return resolveHyperliquidPair(raw) ?? raw;
1779
+ assertString(value, label);
1780
+ if (!/^(?:\d+\.?\d*|\.\d+)$/.test(value.trim())) {
1781
+ throw new Error(`${label} must be a positive decimal string.`);
1728
1782
  }
1729
- if (raw.includes("-")) {
1730
- return resolveHyperliquidPair(raw) ?? raw;
1783
+ const numeric = Number(value);
1784
+ if (!Number.isFinite(numeric) || numeric <= 0) {
1785
+ throw new Error(`${label} must be positive.`);
1731
1786
  }
1732
- return normalizeHyperliquidBaseSymbol(raw) ?? canonicalizeHyperliquidTokenCase(raw);
1733
1787
  }
1734
- function resolveHyperliquidPerpSymbol(asset) {
1735
- const raw = asset.trim();
1736
- if (!raw) return raw;
1737
- const dex = extractHyperliquidDex(raw);
1738
- const base = normalizeHyperliquidBaseSymbol(raw) ?? raw.toUpperCase();
1739
- return dex ? `${dex}:${base}` : base;
1788
+ function collectExchangeErrorMessages(payload) {
1789
+ if (!payload || typeof payload !== "object") return [];
1790
+ const root = payload;
1791
+ const messages = [];
1792
+ const statuses = root.response?.data?.statuses;
1793
+ if (Array.isArray(statuses)) {
1794
+ statuses.forEach((status, index) => {
1795
+ if (status && typeof status === "object" && "error" in status && typeof status.error === "string") {
1796
+ const errorText = status.error;
1797
+ messages.push(`status[${index}]: ${errorText}`);
1798
+ }
1799
+ });
1800
+ }
1801
+ const singleStatus = root.response?.data?.status;
1802
+ if (singleStatus && typeof singleStatus === "object" && "error" in singleStatus && typeof singleStatus.error === "string") {
1803
+ messages.push(singleStatus.error);
1804
+ }
1805
+ return messages;
1740
1806
  }
1741
- function resolveHyperliquidSpotSymbol(asset, defaultQuote = "USDC") {
1742
- const quote = defaultQuote.trim().toUpperCase() || "USDC";
1743
- const raw = asset.trim().toUpperCase();
1744
- if (!raw) {
1745
- return { symbol: raw, base: raw, quote };
1807
+ async function postExchange(env, body) {
1808
+ const response = await fetch(`${API_BASES[env]}/exchange`, {
1809
+ method: "POST",
1810
+ headers: { "content-type": "application/json" },
1811
+ body: JSON.stringify(body)
1812
+ });
1813
+ const text = await response.text().catch(() => "");
1814
+ const json = (() => {
1815
+ if (!text) return null;
1816
+ try {
1817
+ return JSON.parse(text);
1818
+ } catch {
1819
+ return null;
1820
+ }
1821
+ })();
1822
+ if (!response.ok) {
1823
+ throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
1824
+ status: response.status,
1825
+ statusText: response.statusText,
1826
+ body: json ?? (text ? text : null)
1827
+ });
1746
1828
  }
1747
- const pair = resolveHyperliquidPair(raw);
1748
- if (pair) {
1749
- const [base2, pairQuote] = pair.split("/");
1750
- return {
1751
- symbol: pair,
1752
- base: base2?.trim() ?? raw,
1753
- quote: pairQuote?.trim() ?? quote
1754
- };
1829
+ if (!json) {
1830
+ throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
1831
+ status: response.status,
1832
+ statusText: response.statusText,
1833
+ body: text ? text : null
1834
+ });
1755
1835
  }
1756
- const base = normalizeHyperliquidBaseSymbol(raw) ?? raw;
1757
- return { symbol: `${base}/${quote}`, base, quote };
1836
+ if (json.status !== "ok") {
1837
+ throw new HyperliquidApiError("Hyperliquid exchange returned error.", {
1838
+ status: response.status,
1839
+ statusText: response.statusText,
1840
+ body: json
1841
+ });
1842
+ }
1843
+ const nestedErrors = collectExchangeErrorMessages(json);
1844
+ if (nestedErrors.length > 0) {
1845
+ throw new HyperliquidApiError("Hyperliquid exchange returned action errors.", {
1846
+ status: response.status,
1847
+ statusText: response.statusText,
1848
+ body: json,
1849
+ errors: nestedErrors
1850
+ });
1851
+ }
1852
+ return json;
1758
1853
  }
1759
-
1760
- // src/adapters/hyperliquid/actions.ts
1761
1854
  function resolveRequiredNonce(params) {
1762
1855
  if (typeof params.nonce === "number") {
1763
1856
  return params.nonce;
@@ -2908,6 +3001,6 @@ function estimateHyperliquidLiquidationPrice(params) {
2908
3001
  return liquidationPrice;
2909
3002
  }
2910
3003
 
2911
- export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, DEFAULT_HYPERLIQUID_TPSL_MARKET_SLIPPAGE_BPS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidActionHash, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, estimateHyperliquidLiquidationPrice, extractHyperliquidDex, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPreTransferCheck, fetchHyperliquidResolvedMarketDescriptor, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName2 as normalizeSpotTokenName, parseHyperliquidSymbol, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidOrderWithTpSl, placeHyperliquidPositionTpSl, placeHyperliquidTwapOrder, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidLeverageMode, resolveHyperliquidMarketDataCoin, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidPerpSymbol, resolveHyperliquidProfileChain, resolveHyperliquidSpotSymbol, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidPortfolioMargin, supportsHyperliquidBuilderFee, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
3004
+ export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, DEFAULT_HYPERLIQUID_TPSL_MARKET_SLIPPAGE_BPS, HYPERLIQUID_HIP3_DEXES, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidActionHash, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, estimateHyperliquidLiquidationPrice, extractHyperliquidDex, fetchHyperliquidActiveAsset, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidFrontendOpenOrdersAcrossDexes, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOpenOrdersAcrossDexes, fetchHyperliquidOrderStatus, fetchHyperliquidPreTransferCheck, fetchHyperliquidResolvedMarketDescriptor, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, getKnownHyperliquidDexes, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName2 as normalizeSpotTokenName, parseHyperliquidSymbol, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidOrderWithTpSl, placeHyperliquidPositionTpSl, placeHyperliquidTwapOrder, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidLeverageMode, resolveHyperliquidMarketDataCoin, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidPerpSymbol, resolveHyperliquidProfileChain, resolveHyperliquidSpotSymbol, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidPortfolioMargin, supportsHyperliquidBuilderFee, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
2912
3005
  //# sourceMappingURL=browser.js.map
2913
3006
  //# sourceMappingURL=browser.js.map