@basedone/core 0.2.6 → 0.2.8

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.
package/dist/index.mjs CHANGED
@@ -1,8 +1,6 @@
1
- export { BannerType, BaseEcommerceClient, CustomerEcommerceClient, DiscountMethod, DiscountScope, DiscountType, EcommerceApiError, InventoryAuditAction, MerchantEcommerceClient, MerchantStatus, OrderStatus, PaymentMethod, PaymentStatus, ProductSortBy, ReturnStatus, ReviewSortBy, ReviewStatus, ShipmentStatus, SortOrder, TaxBehavior, TaxReportPeriodType, TaxReportStatus, TaxType, buildQueryString, calculateDiscountAmount, calculateFinalPrice, formatPrice, getBackoffDelay, isRetryableError, isValidAddress, isValidEmail, parseError, retryWithBackoff, sleep, truncateAddress } from './chunk-CAU4QLVH.mjs';
1
+ export { BannerType, BaseEcommerceClient, CustomerEcommerceClient, DiscountMethod, DiscountScope, DiscountType, EcommerceApiError, InventoryAuditAction, MerchantBusinessType, MerchantEcommerceClient, MerchantReturnPolicyType, MerchantStatus, OrderStatus, PaymentMethod, PaymentStatus, ProductSortBy, ReturnStatus, ReviewSortBy, ReviewStatus, ShipmentStatus, SortOrder, TaxBehavior, TaxReportPeriodType, TaxReportStatus, TaxType, buildQueryString, calculateDiscountAmount, calculateFinalPrice, formatPrice, getBackoffDelay, isRetryableError, isValidAddress, isValidEmail, parseError, retryWithBackoff, sleep, truncateAddress } from './chunk-NKSQEISP.mjs';
2
2
  export { AssetIdUtils, InstrumentClient } from './chunk-VBC6EQ7Q.mjs';
3
- import { __glob } from './chunk-4UEJOM6W.mjs';
4
3
  import Decimal, { Decimal as Decimal$1 } from 'decimal.js';
5
- import { HttpTransport, InfoClient } from '@nktkas/hyperliquid';
6
4
  import { signL1Action, signUserSignedAction } from '@nktkas/hyperliquid/signing';
7
5
 
8
6
  // lib/cloid/encoder.ts
@@ -545,645 +543,9 @@ var TESTNET_USDC_SPOT_TOKEN = {
545
543
  fullName: null,
546
544
  deployerTradingFeeShare: "0.0"
547
545
  };
548
- function isHip3Symbol(symbol) {
549
- if (!symbol) return false;
550
- return symbol.includes(":");
551
- }
552
- function getHip3Dex(symbol) {
553
- if (!symbol) return null;
554
- return symbol.split(":")[0];
555
- }
556
- async function enableHip3DexAbstractionWithAgent(client) {
557
- const nonce = Date.now();
558
- const action = {
559
- type: "agentEnableDexAbstraction"
560
- };
561
- const signature = await signL1Action({
562
- wallet: client.wallet,
563
- action,
564
- isTestnet: client.isTestnet,
565
- nonce
566
- });
567
- return await client.transport.request("exchange", {
568
- action,
569
- signature,
570
- nonce
571
- });
572
- }
573
- var UserDexAbstractionTypes = {
574
- "HyperliquidTransaction:UserDexAbstraction": [
575
- { name: "hyperliquidChain", type: "string" },
576
- { name: "user", type: "address" },
577
- { name: "enabled", type: "bool" },
578
- { name: "nonce", type: "uint64" }
579
- ]
580
- };
581
- async function setHip3DexAbstraction(client, enabled, user) {
582
- const nonce = Date.now();
583
- const isTestnet = client.isTestnet;
584
- const action = {
585
- type: "userDexAbstraction",
586
- hyperliquidChain: isTestnet ? "Testnet" : "Mainnet",
587
- signatureChainId: isTestnet ? "0x66eee" : "0xa4b1",
588
- user,
589
- enabled,
590
- nonce
591
- };
592
- const signature = await signUserSignedAction({
593
- wallet: client.wallet,
594
- action,
595
- types: UserDexAbstractionTypes
596
- });
597
- return await client.transport.request("exchange", {
598
- action,
599
- signature,
600
- nonce: action.nonce
601
- });
602
- }
603
- async function getHip3DexAbstraction(client, user) {
604
- return await client.transport.request("info", {
605
- type: "userDexAbstraction",
606
- user
607
- });
608
- }
609
- var dexToCollateralTokenSymbol = {
610
- rrrrr: "USDEEE",
611
- hyna: "USDE",
612
- flx: "USDH",
613
- vntl: "USDH"
614
- };
615
- var isSpotSymbol = (coin) => {
616
- if (!coin) return false;
617
- return coin.includes("/") || coin.includes("@");
618
- };
619
- function getStaticCollateralTokenByDex(dex) {
620
- return dexToCollateralTokenSymbol[dex] ?? "USDC";
621
- }
622
- function getStaticCollateralTokenSymbol(coin) {
623
- if (!coin) return "USDC";
624
- if (!isHip3Symbol(coin)) return "USDC";
625
- const dex = getHip3Dex(coin);
626
- if (!dex) return "USDC";
627
- return getStaticCollateralTokenByDex(dex);
628
- }
629
- var stableQuoteTokens = ["USDC", "USDT0", "USDE", "USDEEE", "USDH"];
630
- function isStableQuoteToken(coin) {
631
- return stableQuoteTokens.includes(coin);
632
- }
633
- function getDisplayMarketSymbol(coin, showCollateralTokenSymbol = true, collateralTokenSymbol) {
634
- if (!coin) return coin;
635
- if (isSpotSymbol(coin)) {
636
- if (coin.includes("/")) {
637
- const [baseToken, quoteToken] = coin.split("/");
638
- if (showCollateralTokenSymbol) {
639
- return `${baseToken}/${collateralTokenSymbol ?? quoteToken}`;
640
- } else {
641
- return baseToken;
642
- }
643
- }
644
- return coin;
645
- }
646
- if (isHip3Symbol(coin)) {
647
- const [_, symbol] = coin.split(":");
648
- if (!showCollateralTokenSymbol) return symbol;
649
- return `${symbol}-${collateralTokenSymbol ?? getStaticCollateralTokenSymbol(coin)}`;
650
- }
651
- if (!showCollateralTokenSymbol) return coin;
652
- return `${coin}-USDC`;
653
- }
654
- function getDexFromCollateralTokenSymbol(collateralTokenSymbol) {
655
- return Object.keys(dexToCollateralTokenSymbol).find(
656
- (dex) => dexToCollateralTokenSymbol[dex] === collateralTokenSymbol
657
- );
658
- }
659
-
660
- // import("./data/**/*/staticMeta.json") in lib/meta/metadata.ts
661
- var globImport_data_staticMeta_json = __glob({
662
- "./data/mainnet/staticMeta.json": () => import('./staticMeta-QV2KMX57.mjs'),
663
- "./data/testnet/staticMeta.json": () => import('./staticMeta-GM7T3OYL.mjs')
664
- });
665
-
666
- // import("./data/**/*/spotMeta.json") in lib/meta/metadata.ts
667
- var globImport_data_spotMeta_json = __glob({
668
- "./data/mainnet/spotMeta.json": () => import('./spotMeta-GHXX7C5M.mjs'),
669
- "./data/testnet/spotMeta.json": () => import('./spotMeta-IBBUP2SG.mjs')
670
- });
671
-
672
- // import("./data/**/*/meta.json") in lib/meta/metadata.ts
673
- var globImport_data_meta_json = __glob({
674
- "./data/mainnet/meta.json": () => import('./meta-UOGUG3OW.mjs'),
675
- "./data/testnet/meta.json": () => import('./meta-JB5ITE27.mjs')
676
- });
677
-
678
- // import("./data/**/*/perpDexs.json") in lib/meta/metadata.ts
679
- var globImport_data_perpDexs_json = __glob({
680
- "./data/mainnet/perpDexs.json": () => import('./perpDexs-3LRJ5ZHM.mjs'),
681
- "./data/testnet/perpDexs.json": () => import('./perpDexs-4ISLD7NX.mjs')
682
- });
683
546
 
684
547
  // lib/meta/metadata.ts
685
548
  var ROOT_DEX = "hyperliquid";
686
- var MetadataClient = class {
687
- constructor(config = {}) {
688
- // Core metadata
689
- this.spotMeta = null;
690
- this.perpsMeta = null;
691
- this.perpDexs = [];
692
- this.staticMeta = null;
693
- // HIP-3 metadata cache
694
- this.hip3DexsMeta = /* @__PURE__ */ new Map();
695
- // Pre-computed lookup maps (populated on initialize)
696
- this.perpsSymbolToIndex = /* @__PURE__ */ new Map();
697
- this.spotTokenNameToIndex = /* @__PURE__ */ new Map();
698
- this.spotPairToMarket = /* @__PURE__ */ new Map();
699
- this.baseTokenToMarkets = /* @__PURE__ */ new Map();
700
- this.quoteAssets = [];
701
- // Unified symbol lookup (used by getMarketBySymbol for O(1) access)
702
- // Maps symbol to MarketInfo for quick lookups
703
- this.coinToMarket = /* @__PURE__ */ new Map();
704
- // HIP-3 optimized lookups
705
- // Maps "dex:coin" symbol to MarketInfo
706
- this.hip3SymbolToMarket = /* @__PURE__ */ new Map();
707
- // Maps dex name to dex index for quick lookups
708
- this.dexNameToIndex = /* @__PURE__ */ new Map();
709
- // Lazy init flag
710
- this.initialized = false;
711
- this.initializing = null;
712
- const transport = new HttpTransport({
713
- isTestnet: config.isTestnet ?? false
714
- });
715
- this.infoClient = new InfoClient({ transport });
716
- this.config = {
717
- ...config,
718
- hip3Dexs: config.hip3Dexs?.filter((dex) => dex !== ROOT_DEX),
719
- useStaticFallback: config.useStaticFallback ?? true
720
- };
721
- this.isTestnet = config.isTestnet ?? false;
722
- this.initialize();
723
- }
724
- /**
725
- * Initialize metadata by fetching from Hyperliquid
726
- */
727
- async initialize() {
728
- if (this.initialized) return;
729
- if (this.initializing) return this.initializing;
730
- this.initializing = new Promise(async (resolve, reject) => {
731
- if (this.config.debug) {
732
- console.info("[MetadataClient] Initializing...", this.config);
733
- }
734
- await this.loadStaticMetaOverrides();
735
- if (this.config.onlyUseStaticFallback) {
736
- await this.loadStaticMetadata();
737
- this.buildLookupMaps();
738
- if (this.config.hip3Dexs && this.config.hip3Dexs.length > 0) {
739
- await Promise.all(
740
- this.config.hip3Dexs.map((dex) => this.loadHip3Metadata(dex))
741
- );
742
- }
743
- resolve();
744
- this.initialized = true;
745
- return;
746
- }
747
- try {
748
- [this.spotMeta, this.perpsMeta, this.perpDexs] = await Promise.all([
749
- this.infoClient.spotMeta(),
750
- this.infoClient.meta(),
751
- this.infoClient.perpDexs()
752
- ]);
753
- if (this.config.debug) {
754
- console.info(
755
- "[MetadataClient] Core metadata",
756
- this.spotMeta,
757
- this.perpsMeta,
758
- this.perpDexs
759
- );
760
- }
761
- this.buildLookupMaps();
762
- if (this.config.hip3Dexs && this.config.hip3Dexs.length > 0) {
763
- await Promise.all(
764
- this.config.hip3Dexs.map((dex) => this.loadHip3Metadata(dex))
765
- );
766
- }
767
- this.initialized = true;
768
- if (this.config.debug) {
769
- console.info("[MetadataClient] Initialized");
770
- }
771
- resolve();
772
- } catch (error) {
773
- if (this.config.useStaticFallback) {
774
- console.warn(
775
- "Failed to fetch metadata from API, using static fallback data",
776
- error
777
- );
778
- await this.loadStaticMetadata();
779
- this.buildLookupMaps();
780
- this.initialized = true;
781
- resolve();
782
- } else {
783
- reject(error);
784
- }
785
- } finally {
786
- this.initialized = true;
787
- resolve();
788
- }
789
- });
790
- return this.initializing;
791
- }
792
- /**
793
- * Load staticMeta.json for display overrides
794
- * This is always loaded regardless of config.useStaticFallback
795
- */
796
- async loadStaticMetaOverrides() {
797
- const network = this.isTestnet ? "testnet" : "mainnet";
798
- try {
799
- const staticMetaModule = await globImport_data_staticMeta_json(`./data/${network}/staticMeta.json`);
800
- this.staticMeta = staticMetaModule.default;
801
- if (this.config.debug) {
802
- console.info(
803
- "[MetadataClient] Loaded static metadata overrides",
804
- this.staticMeta
805
- );
806
- }
807
- } catch (error) {
808
- console.warn(`Failed to load staticMeta.json for ${network}:`, error);
809
- this.staticMeta = null;
810
- }
811
- }
812
- /**
813
- * Load static metadata from bundled JSON files
814
- */
815
- async loadStaticMetadata() {
816
- const network = this.isTestnet ? "testnet" : "mainnet";
817
- try {
818
- const [
819
- spotMetaModule,
820
- perpsMetaModule,
821
- perpDexsModule,
822
- staticMetaModule
823
- ] = await Promise.all([
824
- globImport_data_spotMeta_json(`./data/${network}/spotMeta.json`),
825
- globImport_data_meta_json(`./data/${network}/meta.json`),
826
- globImport_data_perpDexs_json(`./data/${network}/perpDexs.json`),
827
- globImport_data_staticMeta_json(`./data/${network}/staticMeta.json`)
828
- ]);
829
- this.spotMeta = spotMetaModule.default;
830
- this.perpsMeta = perpsMetaModule.default;
831
- this.perpDexs = perpDexsModule.default;
832
- this.staticMeta = staticMetaModule.default;
833
- console.warn(`[MetadataClient] Using static ${network} metadata`);
834
- } catch (error) {
835
- console.error(`Failed to load static ${network} metadata:`, error);
836
- throw new Error(`Could not load metadata for ${network}`);
837
- }
838
- }
839
- /**
840
- * Build optimized lookup maps from raw metadata
841
- * Called after metadata is loaded (from API or static files)
842
- */
843
- buildLookupMaps() {
844
- this.perpsSymbolToIndex.clear();
845
- this.spotTokenNameToIndex.clear();
846
- this.spotPairToMarket.clear();
847
- this.baseTokenToMarkets.clear();
848
- this.coinToMarket.clear();
849
- this.dexNameToIndex.clear();
850
- this.quoteAssets = [];
851
- if (this.config.debug) {
852
- console.info(
853
- "[MetadataClient] Building lookup maps",
854
- this.perpDexs,
855
- this.perpsMeta,
856
- this.spotMeta
857
- );
858
- }
859
- if (this.perpDexs) {
860
- this.perpDexs.forEach((dex, index) => {
861
- if (dex && dex.name) {
862
- this.dexNameToIndex.set(dex.name.toLowerCase(), index);
863
- }
864
- });
865
- }
866
- if (this.perpsMeta) {
867
- this.perpsMeta.universe.forEach((market, index) => {
868
- const marketInfo = {
869
- symbol: market.name,
870
- coin: market.name,
871
- assetId: index,
872
- szDecimals: market.szDecimals,
873
- type: "perps",
874
- maxLeverage: market.maxLeverage,
875
- growthMode: market.growthMode === "enabled"
876
- };
877
- const staticOverrides = this.staticMeta?.coins?.[market.name];
878
- if (staticOverrides) {
879
- if (staticOverrides.displayName) {
880
- marketInfo.displayName = staticOverrides.displayName;
881
- }
882
- if (staticOverrides.imageUrl) {
883
- marketInfo.imageUrl = staticOverrides.imageUrl;
884
- }
885
- }
886
- this.perpsSymbolToIndex.set(market.name.toUpperCase(), index);
887
- this.coinToMarket.set(market.name, marketInfo);
888
- });
889
- }
890
- if (this.spotMeta) {
891
- this.spotMeta.tokens.forEach((token) => {
892
- this.spotTokenNameToIndex.set(token.name.toUpperCase(), token.index);
893
- });
894
- const quoteIndices = /* @__PURE__ */ new Set();
895
- this.spotMeta.universe.forEach((universe) => {
896
- const baseToken = this.spotMeta.tokens[universe.tokens[0]];
897
- const quoteToken = this.spotMeta.tokens[universe.tokens[1]];
898
- if (!baseToken || !quoteToken) return;
899
- const coin = universe.name;
900
- quoteIndices.add(quoteToken.index);
901
- const marketInfo = {
902
- coin,
903
- symbol: `${baseToken.name}/${quoteToken.name}`,
904
- assetId: 1e4 + universe.index,
905
- szDecimals: baseToken.szDecimals,
906
- type: "spot",
907
- baseToken,
908
- quoteToken,
909
- growthMode: false
910
- };
911
- const staticOverrides = this.staticMeta?.coins?.[coin];
912
- if (staticOverrides) {
913
- if (staticOverrides.displayName) {
914
- marketInfo.displayName = staticOverrides.displayName;
915
- }
916
- if (staticOverrides.imageUrl) {
917
- marketInfo.imageUrl = staticOverrides.imageUrl;
918
- }
919
- }
920
- const pairKey = `${baseToken.name}/${quoteToken.name}`.toUpperCase();
921
- this.spotPairToMarket.set(pairKey, marketInfo);
922
- this.coinToMarket.set(pairKey, marketInfo);
923
- this.coinToMarket.set(coin, marketInfo);
924
- const baseKey = baseToken.name.toUpperCase();
925
- const existing = this.baseTokenToMarkets.get(baseKey) || [];
926
- existing.push(marketInfo);
927
- this.baseTokenToMarkets.set(baseKey, existing);
928
- });
929
- this.quoteAssets = Array.from(quoteIndices).map((idx) => this.spotMeta.tokens[idx].name).sort();
930
- }
931
- }
932
- /**
933
- * Load metadata for a specific HIP-3 DEX
934
- * Also builds optimized lookups for this DEX's markets
935
- */
936
- async loadHip3Metadata(dexName) {
937
- if (this.hip3DexsMeta.has(dexName)) return this.hip3DexsMeta.get(dexName);
938
- try {
939
- const [meta, contexts] = await this.infoClient.metaAndAssetCtxs({
940
- dex: dexName
941
- });
942
- if (this.config.debug) {
943
- console.info(
944
- "[MetadataClient] Loaded HIP-3 metadata",
945
- dexName,
946
- meta,
947
- contexts
948
- );
949
- }
950
- let dexIndex = this.dexNameToIndex.get(dexName.toLowerCase());
951
- if (dexIndex === void 0) {
952
- dexIndex = this.perpDexs.findIndex(
953
- (d) => d && d.name.toLowerCase() === dexName.toLowerCase()
954
- );
955
- }
956
- if (dexIndex === -1 || dexIndex === void 0) {
957
- throw new Error(`DEX ${dexName} not found`);
958
- }
959
- const dex = this.perpDexs[dexIndex];
960
- const collateralTokenIndex = meta.collateralToken ?? 0;
961
- const spotMetaTokens = this.spotMeta?.tokens;
962
- const collateralTokenSymbol = spotMetaTokens?.[collateralTokenIndex]?.name ?? "USDC";
963
- const dexInfo = {
964
- meta,
965
- assetContext: contexts,
966
- collateralTokenSymbol,
967
- dexFullName: dex?.fullName ?? dexName,
968
- dexName: dex?.name ?? dexName,
969
- dexIndex
970
- };
971
- const staticDexOverrides = this.staticMeta?.dexs?.[dexName];
972
- if (staticDexOverrides) {
973
- if (staticDexOverrides.displayName) {
974
- dexInfo.displayName = staticDexOverrides.displayName;
975
- }
976
- if (staticDexOverrides.imageUrl) {
977
- dexInfo.imageUrl = staticDexOverrides.imageUrl;
978
- }
979
- if (staticDexOverrides.accountName) {
980
- dexInfo.accountName = staticDexOverrides.accountName;
981
- }
982
- }
983
- this.hip3DexsMeta.set(dexName, dexInfo);
984
- this.buildHip3MarketsForDex(dexName, dexInfo);
985
- return dexInfo;
986
- } catch (error) {
987
- console.error(`Failed to load HIP-3 metadata for ${dexName}:`, error);
988
- throw error;
989
- }
990
- }
991
- /**
992
- * Build optimized lookups for HIP-3 markets of a specific DEX
993
- */
994
- buildHip3MarketsForDex(dexName, dexInfo) {
995
- dexInfo.meta.universe.forEach((market, index) => {
996
- const symbol = market.name;
997
- const marketInfo = {
998
- coin: symbol,
999
- symbol,
1000
- assetId: 1e5 + dexInfo.dexIndex * 1e4 + index,
1001
- szDecimals: market.szDecimals,
1002
- type: "hip3",
1003
- maxLeverage: market.maxLeverage,
1004
- dexName,
1005
- dexIndex: dexInfo.dexIndex,
1006
- dexDisplayName: dexInfo.displayName,
1007
- dexImageUrl: dexInfo.imageUrl,
1008
- dexCollateralTokenSymbol: dexInfo.collateralTokenSymbol,
1009
- growthMode: market.growthMode === "enabled"
1010
- };
1011
- const staticOverrides = this.staticMeta?.coins?.[symbol];
1012
- if (staticOverrides) {
1013
- if (staticOverrides.displayName) {
1014
- marketInfo.displayName = staticOverrides.displayName;
1015
- }
1016
- if (staticOverrides.imageUrl) {
1017
- marketInfo.imageUrl = staticOverrides.imageUrl;
1018
- }
1019
- }
1020
- if (this.config.debug) {
1021
- console.info("[MetadataClient] caching market", symbol, marketInfo);
1022
- }
1023
- this.coinToMarket.set(symbol, marketInfo);
1024
- this.hip3SymbolToMarket.set(symbol, marketInfo);
1025
- });
1026
- }
1027
- /**
1028
- * Ensure metadata is loaded (for lazy init)
1029
- */
1030
- async ensureInitialized() {
1031
- if (!this.initialized) {
1032
- await this.initialize();
1033
- }
1034
- }
1035
- /**
1036
- * Get market information by symbol
1037
- * Optimized: O(1) direct map lookup for most cases
1038
- * Lazily initialize hip-3 metadata if not already initialized
1039
- *
1040
- * @param symbol - Market symbol (e.g., "BTC", "PURR/USDC", "vntls:ABC")
1041
- * @param quoteAsset - Quote asset for spot markets (default: "USDC")
1042
- * @returns Market information or null if not found
1043
- */
1044
- async getMarketBySymbolAsync(symbol, quoteAsset = "USDC") {
1045
- await this.ensureInitialized();
1046
- if (symbol.includes(":")) {
1047
- return this.getHip3Market(symbol);
1048
- }
1049
- let lookupKey = symbol.toUpperCase();
1050
- if (!symbol.includes("/") && !symbol.includes("@")) {
1051
- const perpsMarket = this.coinToMarket.get(symbol);
1052
- if (perpsMarket?.type === "perps") {
1053
- return perpsMarket;
1054
- }
1055
- lookupKey = `${symbol}/${quoteAsset}`.toUpperCase();
1056
- }
1057
- return this.coinToMarket.get(lookupKey) || null;
1058
- }
1059
- getMarketByCoin(coin) {
1060
- return this.coinToMarket.get(coin) || null;
1061
- }
1062
- /**
1063
- * Get perpetuals market information
1064
- * Optimized: O(1) map lookup instead of O(n) array search
1065
- */
1066
- getPerpsMarket(symbol) {
1067
- if (!this.perpsMeta) return null;
1068
- if (isHip3Symbol(symbol)) {
1069
- const [dexName, coinName] = symbol.split(":");
1070
- if (!dexName || !coinName) return null;
1071
- let cachedMarket = this.hip3SymbolToMarket.get(symbol);
1072
- return cachedMarket || null;
1073
- }
1074
- const index = this.perpsSymbolToIndex.get(symbol.toUpperCase());
1075
- if (index === void 0) return null;
1076
- const market = this.perpsMeta.universe[index];
1077
- return {
1078
- coin: symbol,
1079
- symbol: market.name,
1080
- assetId: index,
1081
- // Perps asset ID is just the index
1082
- szDecimals: market.szDecimals,
1083
- type: "perps",
1084
- maxLeverage: market.maxLeverage,
1085
- growthMode: market.growthMode === "enabled"
1086
- };
1087
- }
1088
- /**
1089
- * Get spot market information
1090
- * Optimized: O(1) map lookup instead of O(n) array searches
1091
- *
1092
- * @param baseSymbol - Base token symbol (e.g., "PURR", "UHYPE")
1093
- * @param quoteSymbol - Quote token symbol (default: "USDC")
1094
- */
1095
- getSpotMarket(baseSymbol, quoteSymbol = "USDC") {
1096
- if (!this.spotMeta) return null;
1097
- const pairKey = `${baseSymbol}/${quoteSymbol}`.toUpperCase();
1098
- const market = this.spotPairToMarket.get(pairKey);
1099
- return market || null;
1100
- }
1101
- /**
1102
- * Get HIP-3 market information
1103
- * Optimized: O(1) map lookup after DEX metadata is loaded
1104
- *
1105
- * @param symbol - HIP-3 market symbol (format: "dex:coin")
1106
- */
1107
- async getHip3Market(symbol) {
1108
- const [dexName, coinName] = symbol.split(":");
1109
- if (!dexName || !coinName) return null;
1110
- let cachedMarket = this.hip3SymbolToMarket.get(symbol);
1111
- if (cachedMarket) return cachedMarket;
1112
- console.warn("Missing market", symbol, this.hip3SymbolToMarket);
1113
- const dexMeta = this.hip3DexsMeta.get(dexName);
1114
- if (!dexMeta && this.config.lazyInit) {
1115
- await this.loadHip3Metadata(dexName);
1116
- cachedMarket = this.hip3SymbolToMarket.get(symbol);
1117
- return cachedMarket || null;
1118
- }
1119
- return null;
1120
- }
1121
- async getHip3Dex(dexName) {
1122
- await this.ensureInitialized();
1123
- let dexInfo = this.hip3DexsMeta.get(dexName) ?? null;
1124
- if (this.config.lazyInit && !dexInfo) {
1125
- dexInfo = await this.loadHip3Metadata(dexName);
1126
- }
1127
- return dexInfo;
1128
- }
1129
- /**
1130
- * Get all available markets for a base token
1131
- * Optimized: O(1) map lookup instead of O(n) filter + map
1132
- * Useful for showing all quote asset options
1133
- */
1134
- getAllMarketsForBase(baseSymbol) {
1135
- if (!this.spotMeta) return [];
1136
- const baseKey = baseSymbol.toUpperCase();
1137
- return this.baseTokenToMarkets.get(baseKey) || [];
1138
- }
1139
- /**
1140
- * Get spot token information
1141
- * Optimized: O(1) map lookup instead of O(n) array search
1142
- */
1143
- getSpotTokenInfo(tokenSymbol) {
1144
- if (!this.spotMeta) return null;
1145
- const tokenIndex = this.spotTokenNameToIndex.get(tokenSymbol.toUpperCase());
1146
- if (tokenIndex === void 0) return null;
1147
- const token = this.spotMeta.tokens[tokenIndex];
1148
- return {
1149
- name: token.name,
1150
- index: token.index,
1151
- szDecimals: token.szDecimals,
1152
- weiDecimals: token.weiDecimals,
1153
- tokenId: token.tokenId
1154
- };
1155
- }
1156
- /**
1157
- * Get all available quote assets
1158
- * Optimized: O(1) pre-computed array instead of O(n) computation
1159
- */
1160
- getAvailableQuoteAssets() {
1161
- return this.quoteAssets;
1162
- }
1163
- /**
1164
- * Get raw metadata (for advanced use cases)
1165
- */
1166
- getRawMetadata() {
1167
- return {
1168
- spotMeta: this.spotMeta,
1169
- perpsMeta: this.perpsMeta,
1170
- perpDexs: this.perpDexs,
1171
- hip3DexsMeta: Object.fromEntries(this.hip3DexsMeta),
1172
- coinToMarket: Object.fromEntries(this.coinToMarket),
1173
- hip3SymbolToMarket: Object.fromEntries(this.hip3SymbolToMarket)
1174
- };
1175
- }
1176
- /**
1177
- * Get network configuration
1178
- */
1179
- getNetworkInfo() {
1180
- return {
1181
- isTestnet: this.isTestnet,
1182
- useStaticFallback: this.config.useStaticFallback,
1183
- initialized: this.initialized
1184
- };
1185
- }
1186
- };
1187
549
  var formatPriceAndSize = ({
1188
550
  px,
1189
551
  sz,
@@ -1303,6 +665,119 @@ function getWeekInfoFromNumber(weekNumber, weekStartsOn = 4 /* Thursday */) {
1303
665
  const endDate = new Date(startDate.getTime() + WEEK_IN_MS);
1304
666
  return { weekNumber, startDate, endDate };
1305
667
  }
668
+ function isHip3Symbol(symbol) {
669
+ if (!symbol) return false;
670
+ return symbol.includes(":");
671
+ }
672
+ function getHip3Dex(symbol) {
673
+ if (!symbol) return null;
674
+ return symbol.split(":")[0];
675
+ }
676
+ async function enableHip3DexAbstractionWithAgent(client) {
677
+ const nonce = Date.now();
678
+ const action = {
679
+ type: "agentEnableDexAbstraction"
680
+ };
681
+ const signature = await signL1Action({
682
+ wallet: client.wallet,
683
+ action,
684
+ isTestnet: client.isTestnet,
685
+ nonce
686
+ });
687
+ return await client.transport.request("exchange", {
688
+ action,
689
+ signature,
690
+ nonce
691
+ });
692
+ }
693
+ var UserDexAbstractionTypes = {
694
+ "HyperliquidTransaction:UserDexAbstraction": [
695
+ { name: "hyperliquidChain", type: "string" },
696
+ { name: "user", type: "address" },
697
+ { name: "enabled", type: "bool" },
698
+ { name: "nonce", type: "uint64" }
699
+ ]
700
+ };
701
+ async function setHip3DexAbstraction(client, enabled, user) {
702
+ const nonce = Date.now();
703
+ const isTestnet = client.isTestnet;
704
+ const action = {
705
+ type: "userDexAbstraction",
706
+ hyperliquidChain: isTestnet ? "Testnet" : "Mainnet",
707
+ signatureChainId: isTestnet ? "0x66eee" : "0xa4b1",
708
+ user,
709
+ enabled,
710
+ nonce
711
+ };
712
+ const signature = await signUserSignedAction({
713
+ wallet: client.wallet,
714
+ action,
715
+ types: UserDexAbstractionTypes
716
+ });
717
+ return await client.transport.request("exchange", {
718
+ action,
719
+ signature,
720
+ nonce: action.nonce
721
+ });
722
+ }
723
+ async function getHip3DexAbstraction(client, user) {
724
+ return await client.transport.request("info", {
725
+ type: "userDexAbstraction",
726
+ user
727
+ });
728
+ }
729
+ var dexToCollateralTokenSymbol = {
730
+ rrrrr: "USDEEE",
731
+ hyna: "USDE",
732
+ flx: "USDH",
733
+ vntl: "USDH",
734
+ km: "USDH",
735
+ cash: "USDT0"
736
+ };
737
+ var isSpotSymbol = (coin) => {
738
+ if (!coin) return false;
739
+ return coin.includes("/") || coin.includes("@");
740
+ };
741
+ function getStaticCollateralTokenByDex(dex) {
742
+ return dexToCollateralTokenSymbol[dex] ?? "USDC";
743
+ }
744
+ function getStaticCollateralTokenSymbol(coin) {
745
+ if (!coin) return "USDC";
746
+ if (!isHip3Symbol(coin)) return "USDC";
747
+ const dex = getHip3Dex(coin);
748
+ if (!dex) return "USDC";
749
+ return getStaticCollateralTokenByDex(dex);
750
+ }
751
+ var stableQuoteTokens = ["USDC", "USDT0", "USDE", "USDEEE", "USDH"];
752
+ function isStableQuoteToken(coin) {
753
+ return stableQuoteTokens.includes(coin);
754
+ }
755
+ function getDisplayMarketSymbol(coin, showCollateralTokenSymbol = true, collateralTokenSymbol) {
756
+ if (!coin) return coin;
757
+ if (isSpotSymbol(coin)) {
758
+ if (coin.includes("/")) {
759
+ const [baseToken, quoteToken] = coin.split("/");
760
+ if (showCollateralTokenSymbol) {
761
+ return `${baseToken}/${collateralTokenSymbol ?? quoteToken}`;
762
+ } else {
763
+ return baseToken;
764
+ }
765
+ }
766
+ return coin;
767
+ }
768
+ if (isHip3Symbol(coin)) {
769
+ const [_, symbol] = coin.split(":");
770
+ if (!showCollateralTokenSymbol) return symbol;
771
+ return `${symbol}-${collateralTokenSymbol ?? getStaticCollateralTokenSymbol(coin)}`;
772
+ }
773
+ if (!showCollateralTokenSymbol) return coin;
774
+ return `${coin}-USDC`;
775
+ }
776
+ function getDexFromCollateralTokenSymbol(collateralTokenSymbol) {
777
+ return Object.keys(dexToCollateralTokenSymbol).find(
778
+ (dex) => dexToCollateralTokenSymbol[dex] === collateralTokenSymbol
779
+ );
780
+ }
1306
781
 
1307
782
  // lib/hip3/market-info.ts
1308
783
  async function getAllPerpsMeta(infoClient) {
@@ -1311,4 +786,4 @@ async function getAllPerpsMeta(infoClient) {
1311
786
  });
1312
787
  }
1313
788
 
1314
- export { CloidClientCode, CloidClientCodeNameById, DayOfWeek, MetadataClient, PUP_TOKEN_ADDRESS, PUP_TOKEN_THRESHOLDS, ROOT_DEX, TARGET_APPROVED_MAX_BUILDER_FEE, TARGET_APPROVED_MAX_BUILDER_FEE_PERCENT, TESTNET_USDC_SPOT_TOKEN, USDC_SPOT_TOKEN, UserDexAbstractionTypes, WidgetType, WidgetTypeById, XP_BOOST_PERCENTAGES, buildCloid, calculateBoostPercentage, calculateTotalPupAmount, decodeSlug, enableHip3DexAbstractionWithAgent, encodeSlug, floorUtcDay, floorUtcHour, floorUtcMinutes, floorUtcWeek, formatPriceAndSize, formatPriceForDisplay, formatPriceForOrder, formatSizeForDisplay, formatSizeForOrder, getAllPerpsMeta, getApprovalAmount, getClientCodeNameById, getCloid, getDexFromCollateralTokenSymbol, getDisplayMarketSymbol, getHip3Dex, getHip3DexAbstraction, getLatestCompletedWeek, getNextTierInfo, getPriceDecimals, getStaticCollateralTokenByDex, getStaticCollateralTokenSymbol, getWeekInfoFromNumber, getWidgetTypeById, isBasedCloid, isClientCode, isHip3Symbol, isMiniAppCloid, isMiniAppTriggeredCloid, isSpotSymbol, isStableQuoteToken, isTenantCloid, isTrackingIdCloid, isWidgetType, makeUtcRounder, normaliseSlug, normaliseTrackingId, normalizeAirdropAmount, parseCloid, setHip3DexAbstraction, stableQuoteTokens };
789
+ export { CloidClientCode, CloidClientCodeNameById, DayOfWeek, PUP_TOKEN_ADDRESS, PUP_TOKEN_THRESHOLDS, ROOT_DEX, TARGET_APPROVED_MAX_BUILDER_FEE, TARGET_APPROVED_MAX_BUILDER_FEE_PERCENT, TESTNET_USDC_SPOT_TOKEN, USDC_SPOT_TOKEN, UserDexAbstractionTypes, WidgetType, WidgetTypeById, XP_BOOST_PERCENTAGES, buildCloid, calculateBoostPercentage, calculateTotalPupAmount, decodeSlug, enableHip3DexAbstractionWithAgent, encodeSlug, floorUtcDay, floorUtcHour, floorUtcMinutes, floorUtcWeek, formatPriceAndSize, formatPriceForDisplay, formatPriceForOrder, formatSizeForDisplay, formatSizeForOrder, getAllPerpsMeta, getApprovalAmount, getClientCodeNameById, getCloid, getDexFromCollateralTokenSymbol, getDisplayMarketSymbol, getHip3Dex, getHip3DexAbstraction, getLatestCompletedWeek, getNextTierInfo, getPriceDecimals, getStaticCollateralTokenByDex, getStaticCollateralTokenSymbol, getWeekInfoFromNumber, getWidgetTypeById, isBasedCloid, isClientCode, isHip3Symbol, isMiniAppCloid, isMiniAppTriggeredCloid, isSpotSymbol, isStableQuoteToken, isTenantCloid, isTrackingIdCloid, isWidgetType, makeUtcRounder, normaliseSlug, normaliseTrackingId, normalizeAirdropAmount, parseCloid, setHip3DexAbstraction, stableQuoteTokens };