@limitless-exchange/sdk 0.0.2 → 1.0.1

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.d.ts CHANGED
@@ -1,34 +1,11 @@
1
+ import { AxiosRequestConfig } from 'axios';
1
2
  import { ethers } from 'ethers';
2
- import { AxiosRequestConfig, AxiosResponse } from 'axios';
3
3
 
4
- /**
5
- * Client type for authentication.
6
- * @public
7
- */
8
- type ClientType = 'eoa' | 'base' | 'etherspot';
9
4
  /**
10
5
  * Trading mode for user interface.
11
6
  * @public
12
7
  */
13
8
  type TradingMode = 'SIMPLE' | 'ADVANCED';
14
- /**
15
- * Authentication headers required for login.
16
- * @public
17
- */
18
- interface SignatureHeaders {
19
- /**
20
- * The Ethereum address of the user
21
- */
22
- 'x-account': string;
23
- /**
24
- * The signing message in hex format
25
- */
26
- 'x-signing-message': string;
27
- /**
28
- * The signature generated by signing the message with the user's wallet
29
- */
30
- 'x-signature': string;
31
- }
32
9
  /**
33
10
  * User rank information.
34
11
  * @public
@@ -74,7 +51,7 @@ interface ReferralData {
74
51
  displayName: string;
75
52
  }
76
53
  /**
77
- * User profile information returned after authentication (1:1 with API response).
54
+ * User profile information (1:1 with API response).
78
55
  * @public
79
56
  */
80
57
  interface UserProfile {
@@ -83,13 +60,9 @@ interface UserProfile {
83
60
  */
84
61
  id: number;
85
62
  /**
86
- * User's Ethereum address (EOA)
63
+ * User's Ethereum address
87
64
  */
88
65
  account: string;
89
- /**
90
- * Client type used for authentication
91
- */
92
- client: ClientType;
93
66
  /**
94
67
  * User rank information containing feeRateBps
95
68
  */
@@ -118,10 +91,6 @@ interface UserProfile {
118
91
  * Social media URL
119
92
  */
120
93
  socialUrl?: string;
121
- /**
122
- * Smart wallet address (optional, required for ETHERSPOT client)
123
- */
124
- smartWallet?: string;
125
94
  /**
126
95
  * Trade wallet option
127
96
  */
@@ -182,7 +151,6 @@ interface ModeInfo {
182
151
  *
183
152
  * @remarks
184
153
  * Contains user-specific information needed for creating orders.
185
- * Typically extracted from authentication result.
186
154
  *
187
155
  * @public
188
156
  */
@@ -197,35 +165,6 @@ interface UserData {
197
165
  */
198
166
  feeRateBps: number;
199
167
  }
200
- /**
201
- * Complete authentication result including session and profile.
202
- * @public
203
- */
204
- interface AuthResult {
205
- /**
206
- * Session cookie value (JWT token)
207
- */
208
- sessionCookie: string;
209
- /**
210
- * User profile information
211
- */
212
- profile: UserProfile;
213
- }
214
- /**
215
- * Options for login authentication.
216
- * @public
217
- */
218
- interface LoginOptions {
219
- /**
220
- * Client type to use for authentication
221
- * @defaultValue 'eoa'
222
- */
223
- client?: ClientType;
224
- /**
225
- * Smart wallet address (required when client is 'etherspot')
226
- */
227
- smartWallet?: string;
228
- }
229
168
 
230
169
  /**
231
170
  * Logger interface for SDK integration.
@@ -309,14 +248,6 @@ declare enum OrderType {
309
248
  /** Good-Til-Cancelled: Remain on orderbook until filled or cancelled */
310
249
  GTC = "GTC"
311
250
  }
312
- /**
313
- * Market type enum.
314
- * @public
315
- */
316
- declare enum MarketType {
317
- CLOB = "CLOB",
318
- NEGRISK = "NEGRISK"
319
- }
320
251
  /**
321
252
  * Signature type enum.
322
253
  * @public
@@ -342,11 +273,6 @@ interface BaseOrderArgs {
342
273
  * Order side (BUY or SELL)
343
274
  */
344
275
  side: Side;
345
- /**
346
- * Market type (CLOB or NEGRISK)
347
- * @defaultValue 'CLOB'
348
- */
349
- marketType?: MarketType;
350
276
  /**
351
277
  * Expiration timestamp (0 for no expiration)
352
278
  * @defaultValue '0'
@@ -684,845 +610,915 @@ interface OrderSigningConfig {
684
610
  */
685
611
  chainId: number;
686
612
  /**
687
- * Contract address for verification
613
+ * Contract address for verification (from venue.exchange)
688
614
  */
689
615
  contractAddress: string;
690
- /**
691
- * Market type (CLOB or NEGRISK)
692
- */
693
- marketType: MarketType;
694
616
  }
695
617
 
696
618
  /**
697
- * Market-related types for Limitless Exchange.
698
- * @module types/markets
619
+ * Portfolio and position types for Limitless Exchange.
620
+ * @module types/portfolio
699
621
  */
700
622
  /**
701
- * Collateral token information.
623
+ * Market information for a position.
624
+ *
702
625
  * @public
703
626
  */
704
- interface CollateralToken {
705
- /**
706
- * Token contract address
707
- */
708
- address: string;
709
- /**
710
- * Token decimals
711
- */
712
- decimals: number;
627
+ interface PositionMarket {
713
628
  /**
714
- * Token symbol (e.g., "USDC")
629
+ * Market ID
715
630
  */
716
- symbol: string;
717
- }
718
- /**
719
- * Market creator information.
720
- * @public
721
- */
722
- interface MarketCreator {
631
+ id: number | string;
723
632
  /**
724
- * Creator name
633
+ * Market slug
725
634
  */
726
- name: string;
635
+ slug: string;
727
636
  /**
728
- * Creator image URL
637
+ * Market title
729
638
  */
730
- imageURI?: string;
639
+ title: string;
731
640
  /**
732
- * Creator link URL
641
+ * Market status
733
642
  */
734
- link?: string;
735
- }
736
- /**
737
- * Market metadata.
738
- * @public
739
- */
740
- interface MarketMetadata {
643
+ status?: string;
741
644
  /**
742
- * Fee enabled flag
645
+ * Whether market is closed
743
646
  */
744
- fee: boolean;
647
+ closed: boolean;
745
648
  /**
746
- * Banner flag
649
+ * Market deadline
747
650
  */
748
- isBannered?: boolean;
651
+ deadline: string;
749
652
  /**
750
- * Polymarket arbitrage flag
653
+ * Condition ID
751
654
  */
752
- isPolyArbitrage?: boolean;
655
+ conditionId?: string;
753
656
  /**
754
- * Market making flag
657
+ * Winning outcome index (null if unresolved)
755
658
  */
756
- shouldMarketMake?: boolean;
659
+ winningOutcomeIndex?: number | null;
757
660
  /**
758
- * Opening price for oracle markets
661
+ * Market group information
759
662
  */
760
- openPrice?: string;
663
+ group?: {
664
+ slug?: string;
665
+ title?: string;
666
+ };
761
667
  }
762
668
  /**
763
- * Market settings for CLOB markets.
669
+ * Position details for YES or NO side.
670
+ *
764
671
  * @public
765
672
  */
766
- interface MarketSettings {
673
+ interface PositionSide {
767
674
  /**
768
- * Minimum order size
675
+ * Cost basis (6 decimals)
769
676
  */
770
- minSize: string;
677
+ cost: string;
771
678
  /**
772
- * Maximum spread allowed
679
+ * Fill price (6 decimals for CLOB, decimal string for AMM)
773
680
  */
774
- maxSpread: number;
681
+ fillPrice: string;
775
682
  /**
776
- * Daily reward amount
683
+ * Current market value (6 decimals)
777
684
  */
778
- dailyReward: string;
685
+ marketValue: string;
779
686
  /**
780
- * Rewards epoch duration
687
+ * Realized P&L (6 decimals)
781
688
  */
782
- rewardsEpoch: string;
689
+ realisedPnl: string;
783
690
  /**
784
- * Constant parameter
691
+ * Unrealized P&L (6 decimals)
785
692
  */
786
- c: string;
693
+ unrealizedPnl: string;
787
694
  }
788
695
  /**
789
- * Trade prices for different order types.
696
+ * Token balance for YES or NO side.
697
+ *
790
698
  * @public
791
699
  */
792
- interface TradePrices {
700
+ interface TokenBalance {
793
701
  /**
794
- * Buy prices (market and limit) for yes/no tokens
702
+ * YES token balance (6 decimals)
795
703
  */
796
- buy: {
797
- market: [number, number];
798
- limit: [number, number];
799
- };
704
+ yes: string;
800
705
  /**
801
- * Sell prices (market and limit) for yes/no tokens
706
+ * NO token balance (6 decimals)
802
707
  */
803
- sell: {
804
- market: [number, number];
805
- limit: [number, number];
806
- };
708
+ no: string;
807
709
  }
808
710
  /**
809
- * Price oracle metadata for oracle-based markets.
711
+ * Latest trade information.
712
+ *
810
713
  * @public
811
714
  */
812
- interface PriceOracleMetadata {
715
+ interface LatestTrade {
813
716
  /**
814
- * Asset ticker symbol
717
+ * Latest YES price (0.0 to 1.0)
815
718
  */
816
- ticker: string;
719
+ latestYesPrice: number;
817
720
  /**
818
- * Asset type (e.g., "CRYPTO")
721
+ * Latest NO price (0.0 to 1.0)
819
722
  */
820
- assetType: string;
723
+ latestNoPrice: number;
821
724
  /**
822
- * Pyth Network price feed address
725
+ * Outcome token price (0.0 to 1.0)
823
726
  */
824
- pythAddress: string;
727
+ outcomeTokenPrice: number;
728
+ }
729
+ /**
730
+ * CLOB (Central Limit Order Book) position.
731
+ *
732
+ * @public
733
+ */
734
+ interface CLOBPosition {
825
735
  /**
826
- * Price feed symbol
736
+ * Market information
827
737
  */
828
- symbol: string;
738
+ market: PositionMarket;
829
739
  /**
830
- * Asset name
740
+ * User's wallet address
831
741
  */
832
- name: string;
742
+ makerAddress: string;
833
743
  /**
834
- * Logo URL
744
+ * Position details for YES and NO sides
835
745
  */
836
- logo: string;
837
- }
838
- /**
839
- * Orderbook entry (bid or ask).
840
- * Matches API response format exactly (1:1 parity).
841
- *
842
- * @public
843
- */
844
- interface OrderbookEntry {
746
+ positions: {
747
+ yes: PositionSide;
748
+ no: PositionSide;
749
+ };
845
750
  /**
846
- * Price per share (0-1 range)
751
+ * Token balances
847
752
  */
848
- price: number;
753
+ tokensBalance: TokenBalance;
849
754
  /**
850
- * Size in shares
755
+ * Latest trade information
851
756
  */
852
- size: number;
757
+ latestTrade: LatestTrade;
853
758
  /**
854
- * Order side ("BUY" or "SELL")
759
+ * Active orders information
855
760
  */
856
- side: string;
761
+ orders?: {
762
+ liveOrders: any[];
763
+ totalCollateralLocked: string;
764
+ };
765
+ /**
766
+ * Rewards information
767
+ */
768
+ rewards?: {
769
+ epochs: any[];
770
+ isEarning: boolean;
771
+ };
857
772
  }
858
773
  /**
859
- * Complete orderbook for a market.
860
- * Matches API response format exactly (1:1 parity).
774
+ * AMM (Automated Market Maker) position.
861
775
  *
862
776
  * @public
863
777
  */
864
- interface OrderBook {
778
+ interface AMMPosition {
865
779
  /**
866
- * Bid orders (buy orders) sorted by price descending
780
+ * Market information
867
781
  */
868
- bids: OrderbookEntry[];
782
+ market: PositionMarket;
869
783
  /**
870
- * Ask orders (sell orders) sorted by price ascending
784
+ * User's wallet address
871
785
  */
872
- asks: OrderbookEntry[];
786
+ account: string;
873
787
  /**
874
- * Token ID for the orderbook (YES token)
788
+ * Outcome index (0 for YES, 1 for NO)
875
789
  */
876
- tokenId: string;
790
+ outcomeIndex: number;
877
791
  /**
878
- * Adjusted midpoint price between best bid and ask
792
+ * Collateral amount (decimal string)
879
793
  */
880
- adjustedMidpoint: number;
794
+ collateralAmount: string;
881
795
  /**
882
- * Maximum allowed spread for the market
796
+ * Outcome token amount (decimal string)
883
797
  */
884
- maxSpread: string;
798
+ outcomeTokenAmount: string;
885
799
  /**
886
- * Minimum order size allowed
800
+ * Average fill price (decimal string)
887
801
  */
888
- minSize: string;
802
+ averageFillPrice: string;
889
803
  /**
890
- * Last trade price for the market
804
+ * Total buys cost (decimal string)
891
805
  */
892
- lastTradePrice: number;
893
- }
894
- /**
895
- * Market price information.
896
- * @public
897
- */
898
- interface MarketPrice {
806
+ totalBuysCost: string;
899
807
  /**
900
- * Token ID
808
+ * Total sells cost (decimal string)
901
809
  */
902
- tokenId: string;
810
+ totalSellsCost: string;
903
811
  /**
904
- * Current price
812
+ * Realized P&L (decimal string)
905
813
  */
906
- price: number;
814
+ realizedPnl: string;
907
815
  /**
908
- * Last update timestamp
816
+ * Unrealized P&L (decimal string)
909
817
  */
910
- updatedAt?: string;
818
+ unrealizedPnl: string;
819
+ /**
820
+ * Latest trade information
821
+ */
822
+ latestTrade?: {
823
+ outcomeTokenPrice: string;
824
+ };
911
825
  }
912
826
  /**
913
- * Market outcome information.
827
+ * API response for /portfolio/positions endpoint.
828
+ *
914
829
  * @public
915
830
  */
916
- interface MarketOutcome {
831
+ interface PortfolioPositionsResponse {
917
832
  /**
918
- * Outcome ID
833
+ * AMM positions
919
834
  */
920
- id: number;
835
+ amm: AMMPosition[];
921
836
  /**
922
- * Outcome title
837
+ * CLOB positions
923
838
  */
924
- title: string;
839
+ clob: CLOBPosition[];
925
840
  /**
926
- * Token ID for this outcome
841
+ * Group positions
927
842
  */
928
- tokenId: string;
843
+ group: any[];
929
844
  /**
930
- * Current price
845
+ * User points
931
846
  */
932
- price?: number;
933
- }
934
- /**
935
- * Market token IDs for CLOB markets.
936
- * @public
937
- */
938
- interface MarketTokens {
939
- yes: string;
940
- no: string;
847
+ points?: string;
848
+ /**
849
+ * Accumulative points
850
+ */
851
+ accumulativePoints?: string;
852
+ /**
853
+ * Rewards information
854
+ */
855
+ rewards?: {
856
+ todaysRewards: string;
857
+ rewardsByEpoch: any[];
858
+ rewardsChartData: any[];
859
+ totalUnpaidRewards: string;
860
+ totalUserRewardsLastEpoch: string;
861
+ };
941
862
  }
942
863
  /**
943
- * Complete market information (1:1 with API response).
944
- * Handles both CLOB single markets and NegRisk group markets.
864
+ * Simplified position for unified view.
945
865
  *
946
866
  * @public
947
867
  */
948
- interface Market {
868
+ interface Position {
949
869
  /**
950
- * Market database ID
870
+ * Position type
951
871
  */
952
- id: number;
872
+ type: 'CLOB' | 'AMM';
953
873
  /**
954
- * Market slug identifier
874
+ * Market information
955
875
  */
956
- slug: string;
876
+ market: PositionMarket;
957
877
  /**
958
- * Market title
878
+ * Position side (YES or NO)
959
879
  */
960
- title: string;
880
+ side: 'YES' | 'NO';
961
881
  /**
962
- * Market proxy title
882
+ * Cost basis in USDC (6 decimals)
963
883
  */
964
- proxyTitle: string | null;
884
+ costBasis: number;
965
885
  /**
966
- * Market description
886
+ * Current market value in USDC (6 decimals)
967
887
  */
968
- description?: string;
888
+ marketValue: number;
969
889
  /**
970
- * Collateral token information
890
+ * Unrealized P&L in USDC (6 decimals)
971
891
  */
972
- collateralToken: CollateralToken;
892
+ unrealizedPnl: number;
973
893
  /**
974
- * Human-readable expiration date
894
+ * Realized P&L in USDC (6 decimals)
975
895
  */
976
- expirationDate: string;
896
+ realizedPnl: number;
977
897
  /**
978
- * Expiration timestamp in milliseconds
898
+ * Current price (0.0 to 1.0)
979
899
  */
980
- expirationTimestamp: number;
900
+ currentPrice: number;
981
901
  /**
982
- * Whether market is expired
902
+ * Average entry price (0.0 to 1.0)
983
903
  */
984
- expired?: boolean;
904
+ avgPrice: number;
985
905
  /**
986
- * Creation timestamp
906
+ * Token balance (6 decimals)
987
907
  */
988
- createdAt: string;
908
+ tokenBalance: number;
909
+ }
910
+ /**
911
+ * Portfolio summary statistics.
912
+ *
913
+ * @public
914
+ */
915
+ interface PortfolioSummary {
989
916
  /**
990
- * Last update timestamp
917
+ * Total portfolio value in USDC (6 decimals)
991
918
  */
992
- updatedAt: string;
919
+ totalValue: number;
993
920
  /**
994
- * Market categories
921
+ * Total cost basis in USDC (6 decimals)
995
922
  */
996
- categories: string[];
923
+ totalCostBasis: number;
997
924
  /**
998
- * Market status
925
+ * Total unrealized P&L in USDC (6 decimals)
999
926
  */
1000
- status: string;
927
+ totalUnrealizedPnl: number;
1001
928
  /**
1002
- * Creator information
929
+ * Total realized P&L in USDC (6 decimals)
1003
930
  */
1004
- creator: MarketCreator;
931
+ totalRealizedPnl: number;
1005
932
  /**
1006
- * Market tags
933
+ * Total unrealized P&L percentage
1007
934
  */
1008
- tags: string[];
935
+ totalUnrealizedPnlPercent: number;
1009
936
  /**
1010
- * Trade type (clob or amm)
937
+ * Number of open positions
1011
938
  */
1012
- tradeType: string;
939
+ positionCount: number;
1013
940
  /**
1014
- * Market type (single or group)
941
+ * Number of markets with positions
1015
942
  */
1016
- marketType: string;
943
+ marketCount: number;
1017
944
  /**
1018
- * Priority index for sorting
945
+ * Breakdown by position type
1019
946
  */
1020
- priorityIndex: number;
947
+ breakdown: {
948
+ clob: {
949
+ positions: number;
950
+ value: number;
951
+ pnl: number;
952
+ };
953
+ amm: {
954
+ positions: number;
955
+ value: number;
956
+ pnl: number;
957
+ };
958
+ };
959
+ }
960
+ /**
961
+ * User history entry.
962
+ *
963
+ * Represents various types of user actions:
964
+ * - AMM trades
965
+ * - CLOB trades
966
+ * - Token splits/merges
967
+ * - NegRisk conversions
968
+ *
969
+ * @public
970
+ */
971
+ interface HistoryEntry {
1021
972
  /**
1022
- * Market metadata
973
+ * Entry ID
1023
974
  */
1024
- metadata: MarketMetadata;
975
+ id: string;
1025
976
  /**
1026
- * Trading volume
977
+ * Entry type (trade, split, merge, conversion, etc.)
1027
978
  */
1028
- volume?: string;
979
+ type: string;
1029
980
  /**
1030
- * Formatted trading volume
981
+ * Entry creation timestamp
1031
982
  */
1032
- volumeFormatted?: string;
983
+ createdAt: string;
1033
984
  /**
1034
- * Condition ID (CLOB only)
985
+ * Associated market slug
1035
986
  */
1036
- conditionId?: string;
987
+ marketSlug?: string;
1037
988
  /**
1038
- * NegRisk request ID (CLOB only)
989
+ * Transaction amount
1039
990
  */
1040
- negRiskRequestId?: string | null;
991
+ amount?: string;
1041
992
  /**
1042
- * Token IDs for yes/no outcomes (CLOB only)
1043
- * @example
1044
- * {
1045
- * yes: "27687694610130623013351012526567944730242898906227824547270172934678693687246",
1046
- * no: "9288900480010863316984252765488448624297561656655547117581633191173128271467"
1047
- * }
993
+ * Additional entry details
1048
994
  */
1049
- tokens?: MarketTokens;
995
+ details?: Record<string, any>;
996
+ }
997
+ /**
998
+ * Paginated user history response from /portfolio/history endpoint.
999
+ *
1000
+ * @public
1001
+ */
1002
+ interface HistoryResponse {
1050
1003
  /**
1051
- * Current prices [yes, no] (CLOB only)
1004
+ * List of history entries
1052
1005
  */
1053
- prices?: number[];
1006
+ data: HistoryEntry[];
1054
1007
  /**
1055
- * Trade prices for buy/sell market/limit orders (CLOB only)
1008
+ * Total number of entries
1056
1009
  */
1057
- tradePrices?: TradePrices;
1010
+ totalCount: number;
1011
+ }
1012
+
1013
+ /**
1014
+ * Market-related types for Limitless Exchange.
1015
+ * @module types/markets
1016
+ */
1017
+ /**
1018
+ * Collateral token information.
1019
+ * @public
1020
+ */
1021
+ interface CollateralToken {
1058
1022
  /**
1059
- * Whether market is rewardable (CLOB only)
1023
+ * Token contract address
1060
1024
  */
1061
- isRewardable?: boolean;
1025
+ address: string;
1062
1026
  /**
1063
- * Market settings (CLOB only)
1027
+ * Token decimals
1064
1028
  */
1065
- settings?: MarketSettings;
1029
+ decimals: number;
1066
1030
  /**
1067
- * Market logo URL
1031
+ * Token symbol (e.g., "USDC")
1068
1032
  */
1069
- logo?: string | null;
1033
+ symbol: string;
1034
+ }
1035
+ /**
1036
+ * Market creator information.
1037
+ * @public
1038
+ */
1039
+ interface MarketCreator {
1070
1040
  /**
1071
- * Price oracle metadata (oracle markets only)
1041
+ * Creator name
1072
1042
  */
1073
- priceOracleMetadata?: PriceOracleMetadata;
1043
+ name: string;
1074
1044
  /**
1075
- * Order within group (group markets only)
1045
+ * Creator image URL
1076
1046
  */
1077
- orderInGroup?: number;
1047
+ imageURI?: string;
1078
1048
  /**
1079
- * Winning outcome index
1049
+ * Creator link URL
1080
1050
  */
1081
- winningOutcomeIndex?: number | null;
1051
+ link?: string;
1052
+ }
1053
+ /**
1054
+ * Market metadata.
1055
+ * @public
1056
+ */
1057
+ interface MarketMetadata {
1082
1058
  /**
1083
- * Outcome token names (group only)
1059
+ * Fee enabled flag
1084
1060
  */
1085
- outcomeTokens?: string[];
1061
+ fee: boolean;
1086
1062
  /**
1087
- * OG image URI (group only)
1063
+ * Banner flag
1088
1064
  */
1089
- ogImageURI?: string;
1065
+ isBannered?: boolean;
1090
1066
  /**
1091
- * NegRisk market ID (group only)
1067
+ * Polymarket arbitrage flag
1092
1068
  */
1093
- negRiskMarketId?: string;
1069
+ isPolyArbitrage?: boolean;
1094
1070
  /**
1095
- * Child markets in group (group only)
1071
+ * Market making flag
1096
1072
  */
1097
- markets?: Market[];
1073
+ shouldMarketMake?: boolean;
1098
1074
  /**
1099
- * Daily reward for group (group only)
1075
+ * Opening price for oracle markets
1100
1076
  */
1101
- dailyReward?: string;
1077
+ openPrice?: string;
1078
+ }
1079
+ /**
1080
+ * Market settings for CLOB markets.
1081
+ * @public
1082
+ */
1083
+ interface MarketSettings {
1102
1084
  /**
1103
- * Market contract address
1104
- * @deprecated Use conditionId instead
1085
+ * Minimum order size
1105
1086
  */
1106
- address?: string | null;
1087
+ minSize: string;
1107
1088
  /**
1108
- * Market type (CLOB or AMM)
1109
- * @deprecated Use tradeType instead
1089
+ * Maximum spread allowed
1110
1090
  */
1111
- type?: string;
1091
+ maxSpread: number;
1112
1092
  /**
1113
- * Market outcomes
1114
- * @deprecated Use tokens for CLOB markets
1093
+ * Daily reward amount
1115
1094
  */
1116
- outcomes?: MarketOutcome[];
1095
+ dailyReward: string;
1117
1096
  /**
1118
- * Resolution timestamp
1119
- * @deprecated Use expirationTimestamp instead
1097
+ * Rewards epoch duration
1120
1098
  */
1121
- resolutionDate?: string;
1099
+ rewardsEpoch: string;
1100
+ /**
1101
+ * Constant parameter
1102
+ */
1103
+ c: string;
1122
1104
  }
1123
1105
  /**
1124
- * Markets list response.
1106
+ * Trade prices for different order types.
1125
1107
  * @public
1126
1108
  */
1127
- interface MarketsResponse {
1128
- /**
1129
- * Array of markets
1130
- */
1131
- markets: Market[];
1132
- /**
1133
- * Total count
1134
- */
1135
- total?: number;
1109
+ interface TradePrices {
1136
1110
  /**
1137
- * Pagination offset
1111
+ * Buy prices (market and limit) for yes/no tokens
1138
1112
  */
1139
- offset?: number;
1113
+ buy: {
1114
+ market: [number, number];
1115
+ limit: [number, number];
1116
+ };
1140
1117
  /**
1141
- * Pagination limit
1118
+ * Sell prices (market and limit) for yes/no tokens
1142
1119
  */
1143
- limit?: number;
1120
+ sell: {
1121
+ market: [number, number];
1122
+ limit: [number, number];
1123
+ };
1144
1124
  }
1145
1125
  /**
1146
- * Sort options for active markets.
1147
- * @public
1148
- */
1149
- type ActiveMarketsSortBy = 'lp_rewards' | 'ending_soon' | 'newest' | 'high_value' | 'liquidity';
1150
- /**
1151
- * Query parameters for active markets endpoint.
1126
+ * Price oracle metadata for oracle-based markets.
1152
1127
  * @public
1153
1128
  */
1154
- interface ActiveMarketsParams {
1129
+ interface PriceOracleMetadata {
1155
1130
  /**
1156
- * Maximum number of markets to return (max 25)
1157
- * @defaultValue 25
1131
+ * Asset ticker symbol
1158
1132
  */
1159
- limit?: number;
1133
+ ticker: string;
1160
1134
  /**
1161
- * Page number for pagination (starts at 1)
1162
- * @defaultValue 1
1135
+ * Asset type (e.g., "CRYPTO")
1163
1136
  */
1164
- page?: number;
1137
+ assetType: string;
1165
1138
  /**
1166
- * Sort order for markets
1139
+ * Pyth Network price feed address
1167
1140
  */
1168
- sortBy?: ActiveMarketsSortBy;
1141
+ pythAddress: string;
1142
+ /**
1143
+ * Price feed symbol
1144
+ */
1145
+ symbol: string;
1146
+ /**
1147
+ * Asset name
1148
+ */
1149
+ name: string;
1150
+ /**
1151
+ * Logo URL
1152
+ */
1153
+ logo: string;
1169
1154
  }
1170
1155
  /**
1171
- * Active markets response from API.
1156
+ * Orderbook entry (bid or ask).
1157
+ * Matches API response format exactly (1:1 parity).
1158
+ *
1172
1159
  * @public
1173
1160
  */
1174
- interface ActiveMarketsResponse {
1161
+ interface OrderbookEntry {
1175
1162
  /**
1176
- * Array of active markets
1163
+ * Price per share (0-1 range)
1177
1164
  */
1178
- data: Market[];
1165
+ price: number;
1179
1166
  /**
1180
- * Total count of active markets
1167
+ * Size in shares
1181
1168
  */
1182
- totalMarketsCount: number;
1169
+ size: number;
1170
+ /**
1171
+ * Order side ("BUY" or "SELL")
1172
+ */
1173
+ side: string;
1183
1174
  }
1184
-
1185
- /**
1186
- * Portfolio and position types for Limitless Exchange.
1187
- * @module types/portfolio
1188
- */
1189
1175
  /**
1190
- * Market information for a position.
1176
+ * Complete orderbook for a market.
1177
+ * Matches API response format exactly (1:1 parity).
1191
1178
  *
1192
1179
  * @public
1193
1180
  */
1194
- interface PositionMarket {
1195
- /**
1196
- * Market ID
1197
- */
1198
- id: number | string;
1199
- /**
1200
- * Market slug
1201
- */
1202
- slug: string;
1181
+ interface OrderBook {
1203
1182
  /**
1204
- * Market title
1183
+ * Bid orders (buy orders) sorted by price descending
1205
1184
  */
1206
- title: string;
1185
+ bids: OrderbookEntry[];
1207
1186
  /**
1208
- * Market status
1187
+ * Ask orders (sell orders) sorted by price ascending
1209
1188
  */
1210
- status?: string;
1189
+ asks: OrderbookEntry[];
1211
1190
  /**
1212
- * Whether market is closed
1191
+ * Token ID for the orderbook (YES token)
1213
1192
  */
1214
- closed: boolean;
1193
+ tokenId: string;
1215
1194
  /**
1216
- * Market deadline
1195
+ * Adjusted midpoint price between best bid and ask
1217
1196
  */
1218
- deadline: string;
1197
+ adjustedMidpoint: number;
1219
1198
  /**
1220
- * Condition ID
1199
+ * Maximum allowed spread for the market
1221
1200
  */
1222
- conditionId?: string;
1201
+ maxSpread: string;
1223
1202
  /**
1224
- * Winning outcome index (null if unresolved)
1203
+ * Minimum order size allowed
1225
1204
  */
1226
- winningOutcomeIndex?: number | null;
1205
+ minSize: string;
1227
1206
  /**
1228
- * Market group information
1207
+ * Last trade price for the market
1229
1208
  */
1230
- group?: {
1231
- slug?: string;
1232
- title?: string;
1233
- };
1209
+ lastTradePrice: number;
1234
1210
  }
1235
1211
  /**
1236
- * Position details for YES or NO side.
1237
- *
1212
+ * Market outcome information.
1238
1213
  * @public
1239
1214
  */
1240
- interface PositionSide {
1241
- /**
1242
- * Cost basis (6 decimals)
1243
- */
1244
- cost: string;
1215
+ interface MarketOutcome {
1245
1216
  /**
1246
- * Fill price (6 decimals for CLOB, decimal string for AMM)
1217
+ * Outcome ID
1247
1218
  */
1248
- fillPrice: string;
1219
+ id: number;
1249
1220
  /**
1250
- * Current market value (6 decimals)
1221
+ * Outcome title
1251
1222
  */
1252
- marketValue: string;
1223
+ title: string;
1253
1224
  /**
1254
- * Realized P&L (6 decimals)
1225
+ * Token ID for this outcome
1255
1226
  */
1256
- realisedPnl: string;
1227
+ tokenId: string;
1257
1228
  /**
1258
- * Unrealized P&L (6 decimals)
1229
+ * Current price
1259
1230
  */
1260
- unrealizedPnl: string;
1231
+ price?: number;
1261
1232
  }
1262
1233
  /**
1263
- * Token balance for YES or NO side.
1234
+ * Venue information for CLOB markets.
1235
+ *
1236
+ * @remarks
1237
+ * Contains contract addresses required for trading:
1238
+ * - exchange: Used as verifyingContract for EIP-712 order signing
1239
+ * - adapter: Required for NegRisk/Grouped market SELL approvals
1264
1240
  *
1265
1241
  * @public
1266
1242
  */
1267
- interface TokenBalance {
1243
+ interface Venue {
1268
1244
  /**
1269
- * YES token balance (6 decimals)
1245
+ * Exchange contract address.
1246
+ *
1247
+ * @remarks
1248
+ * This address is used as the verifyingContract in EIP-712 order signing.
1249
+ * All BUY orders require USDC approval to this address.
1250
+ * Simple CLOB SELL orders require CT approval to this address.
1270
1251
  */
1271
- yes: string;
1252
+ exchange: string;
1272
1253
  /**
1273
- * NO token balance (6 decimals)
1254
+ * Adapter contract address.
1255
+ *
1256
+ * @remarks
1257
+ * Required for NegRisk/Grouped markets only.
1258
+ * SELL orders on NegRisk markets require CT approval to both exchange AND adapter.
1274
1259
  */
1260
+ adapter: string;
1261
+ }
1262
+ /**
1263
+ * Market token IDs for CLOB markets.
1264
+ * @public
1265
+ */
1266
+ interface MarketTokens {
1267
+ yes: string;
1275
1268
  no: string;
1276
1269
  }
1277
1270
  /**
1278
- * Latest trade information.
1271
+ * Complete market information (1:1 with API response).
1272
+ * Handles both CLOB single markets and NegRisk group markets.
1279
1273
  *
1280
1274
  * @public
1281
1275
  */
1282
- interface LatestTrade {
1276
+ interface Market$1 {
1283
1277
  /**
1284
- * Latest YES price (0.0 to 1.0)
1278
+ * Market database ID
1285
1279
  */
1286
- latestYesPrice: number;
1280
+ id: number;
1287
1281
  /**
1288
- * Latest NO price (0.0 to 1.0)
1282
+ * Market slug identifier
1289
1283
  */
1290
- latestNoPrice: number;
1284
+ slug: string;
1291
1285
  /**
1292
- * Outcome token price (0.0 to 1.0)
1286
+ * Market title
1293
1287
  */
1294
- outcomeTokenPrice: number;
1295
- }
1296
- /**
1297
- * CLOB (Central Limit Order Book) position.
1298
- *
1299
- * @public
1300
- */
1301
- interface CLOBPosition {
1288
+ title: string;
1302
1289
  /**
1303
- * Market information
1290
+ * Market proxy title
1304
1291
  */
1305
- market: PositionMarket;
1292
+ proxyTitle: string | null;
1306
1293
  /**
1307
- * User's wallet address
1294
+ * Market description
1308
1295
  */
1309
- makerAddress: string;
1296
+ description?: string;
1310
1297
  /**
1311
- * Position details for YES and NO sides
1298
+ * Collateral token information
1312
1299
  */
1313
- positions: {
1314
- yes: PositionSide;
1315
- no: PositionSide;
1316
- };
1300
+ collateralToken: CollateralToken;
1317
1301
  /**
1318
- * Token balances
1302
+ * Human-readable expiration date
1319
1303
  */
1320
- tokensBalance: TokenBalance;
1304
+ expirationDate: string;
1321
1305
  /**
1322
- * Latest trade information
1306
+ * Expiration timestamp in milliseconds
1323
1307
  */
1324
- latestTrade: LatestTrade;
1308
+ expirationTimestamp: number;
1325
1309
  /**
1326
- * Active orders information
1310
+ * Whether market is expired
1327
1311
  */
1328
- orders?: {
1329
- liveOrders: any[];
1330
- totalCollateralLocked: string;
1331
- };
1312
+ expired?: boolean;
1332
1313
  /**
1333
- * Rewards information
1314
+ * Creation timestamp
1334
1315
  */
1335
- rewards?: {
1336
- epochs: any[];
1337
- isEarning: boolean;
1338
- };
1339
- }
1340
- /**
1341
- * AMM (Automated Market Maker) position.
1342
- *
1343
- * @public
1344
- */
1345
- interface AMMPosition {
1316
+ createdAt: string;
1346
1317
  /**
1347
- * Market information
1318
+ * Last update timestamp
1348
1319
  */
1349
- market: PositionMarket;
1320
+ updatedAt: string;
1350
1321
  /**
1351
- * User's wallet address
1322
+ * Market categories
1352
1323
  */
1353
- account: string;
1324
+ categories: string[];
1354
1325
  /**
1355
- * Outcome index (0 for YES, 1 for NO)
1326
+ * Market status
1356
1327
  */
1357
- outcomeIndex: number;
1328
+ status: string;
1358
1329
  /**
1359
- * Collateral amount (decimal string)
1330
+ * Creator information
1360
1331
  */
1361
- collateralAmount: string;
1332
+ creator: MarketCreator;
1362
1333
  /**
1363
- * Outcome token amount (decimal string)
1334
+ * Market tags
1364
1335
  */
1365
- outcomeTokenAmount: string;
1336
+ tags: string[];
1366
1337
  /**
1367
- * Average fill price (decimal string)
1338
+ * Trade type (clob or amm)
1368
1339
  */
1369
- averageFillPrice: string;
1340
+ tradeType: string;
1370
1341
  /**
1371
- * Total buys cost (decimal string)
1342
+ * Market type (single or group)
1372
1343
  */
1373
- totalBuysCost: string;
1344
+ marketType: string;
1374
1345
  /**
1375
- * Total sells cost (decimal string)
1346
+ * Priority index for sorting
1376
1347
  */
1377
- totalSellsCost: string;
1348
+ priorityIndex: number;
1378
1349
  /**
1379
- * Realized P&L (decimal string)
1350
+ * Market metadata
1380
1351
  */
1381
- realizedPnl: string;
1352
+ metadata: MarketMetadata;
1382
1353
  /**
1383
- * Unrealized P&L (decimal string)
1354
+ * Trading volume
1384
1355
  */
1385
- unrealizedPnl: string;
1356
+ volume?: string;
1386
1357
  /**
1387
- * Latest trade information
1358
+ * Formatted trading volume
1388
1359
  */
1389
- latestTrade?: {
1390
- outcomeTokenPrice: string;
1391
- };
1392
- }
1393
- /**
1394
- * API response for /portfolio/positions endpoint.
1395
- *
1396
- * @public
1397
- */
1398
- interface PortfolioPositionsResponse {
1360
+ volumeFormatted?: string;
1399
1361
  /**
1400
- * AMM positions
1362
+ * Condition ID (CLOB only)
1401
1363
  */
1402
- amm: AMMPosition[];
1364
+ conditionId?: string;
1403
1365
  /**
1404
- * CLOB positions
1366
+ * NegRisk request ID (CLOB only)
1405
1367
  */
1406
- clob: CLOBPosition[];
1368
+ negRiskRequestId?: string | null;
1407
1369
  /**
1408
- * Group positions
1370
+ * Token IDs for yes/no outcomes (CLOB only)
1371
+ * @example
1372
+ * {
1373
+ * yes: "27687694610130623013351012526567944730242898906227824547270172934678693687246",
1374
+ * no: "9288900480010863316984252765488448624297561656655547117581633191173128271467"
1375
+ * }
1409
1376
  */
1410
- group: any[];
1377
+ tokens?: MarketTokens;
1411
1378
  /**
1412
- * User points
1379
+ * Current prices [yes, no] (CLOB only)
1413
1380
  */
1414
- points?: string;
1381
+ prices?: number[];
1415
1382
  /**
1416
- * Accumulative points
1383
+ * Trade prices for buy/sell market/limit orders (CLOB only)
1384
+ */
1385
+ tradePrices?: TradePrices;
1386
+ /**
1387
+ * Whether market is rewardable (CLOB only)
1388
+ */
1389
+ isRewardable?: boolean;
1390
+ /**
1391
+ * Market settings (CLOB only)
1392
+ */
1393
+ settings?: MarketSettings;
1394
+ /**
1395
+ * Venue information for CLOB markets.
1396
+ *
1397
+ * @remarks
1398
+ * Contains exchange and adapter contract addresses for order signing and approvals.
1399
+ * The exchange address is used as verifyingContract in EIP-712 signatures.
1400
+ *
1401
+ * Performance tip: Call getMarket() before createOrder() to cache venue data
1402
+ * and avoid additional API requests during order creation.
1403
+ */
1404
+ venue?: Venue;
1405
+ /**
1406
+ * Market logo URL
1407
+ */
1408
+ logo?: string | null;
1409
+ /**
1410
+ * Price oracle metadata (oracle markets only)
1417
1411
  */
1418
- accumulativePoints?: string;
1412
+ priceOracleMetadata?: PriceOracleMetadata;
1419
1413
  /**
1420
- * Rewards information
1414
+ * Order within group (group markets only)
1421
1415
  */
1422
- rewards?: {
1423
- todaysRewards: string;
1424
- rewardsByEpoch: any[];
1425
- rewardsChartData: any[];
1426
- totalUnpaidRewards: string;
1427
- totalUserRewardsLastEpoch: string;
1428
- };
1429
- }
1430
- /**
1431
- * Simplified position for unified view.
1432
- *
1433
- * @public
1434
- */
1435
- interface Position {
1416
+ orderInGroup?: number;
1436
1417
  /**
1437
- * Position type
1418
+ * Winning outcome index
1438
1419
  */
1439
- type: 'CLOB' | 'AMM';
1420
+ winningOutcomeIndex?: number | null;
1440
1421
  /**
1441
- * Market information
1422
+ * Outcome token names (group only)
1442
1423
  */
1443
- market: PositionMarket;
1424
+ outcomeTokens?: string[];
1444
1425
  /**
1445
- * Position side (YES or NO)
1426
+ * OG image URI (group only)
1446
1427
  */
1447
- side: 'YES' | 'NO';
1428
+ ogImageURI?: string;
1448
1429
  /**
1449
- * Cost basis in USDC (6 decimals)
1430
+ * NegRisk market ID (group only)
1450
1431
  */
1451
- costBasis: number;
1432
+ negRiskMarketId?: string;
1452
1433
  /**
1453
- * Current market value in USDC (6 decimals)
1434
+ * Child markets in group (group only)
1454
1435
  */
1455
- marketValue: number;
1436
+ markets?: Market$1[];
1456
1437
  /**
1457
- * Unrealized P&L in USDC (6 decimals)
1438
+ * Daily reward for group (group only)
1458
1439
  */
1459
- unrealizedPnl: number;
1440
+ dailyReward?: string;
1460
1441
  /**
1461
- * Realized P&L in USDC (6 decimals)
1442
+ * Market contract address
1443
+ * @deprecated Use conditionId instead
1462
1444
  */
1463
- realizedPnl: number;
1445
+ address?: string | null;
1464
1446
  /**
1465
- * Current price (0.0 to 1.0)
1447
+ * Market type (CLOB or AMM)
1448
+ * @deprecated Use tradeType instead
1466
1449
  */
1467
- currentPrice: number;
1450
+ type?: string;
1468
1451
  /**
1469
- * Average entry price (0.0 to 1.0)
1452
+ * Market outcomes
1453
+ * @deprecated Use tokens for CLOB markets
1470
1454
  */
1471
- avgPrice: number;
1455
+ outcomes?: MarketOutcome[];
1472
1456
  /**
1473
- * Token balance (6 decimals)
1457
+ * Resolution timestamp
1458
+ * @deprecated Use expirationTimestamp instead
1474
1459
  */
1475
- tokenBalance: number;
1460
+ resolutionDate?: string;
1476
1461
  }
1477
1462
  /**
1478
- * Portfolio summary statistics.
1479
- *
1463
+ * Markets list response.
1480
1464
  * @public
1481
1465
  */
1482
- interface PortfolioSummary {
1466
+ interface MarketsResponse {
1483
1467
  /**
1484
- * Total portfolio value in USDC (6 decimals)
1468
+ * Array of markets
1485
1469
  */
1486
- totalValue: number;
1470
+ markets: Market$1[];
1487
1471
  /**
1488
- * Total cost basis in USDC (6 decimals)
1472
+ * Total count
1489
1473
  */
1490
- totalCostBasis: number;
1474
+ total?: number;
1491
1475
  /**
1492
- * Total unrealized P&L in USDC (6 decimals)
1476
+ * Pagination offset
1493
1477
  */
1494
- totalUnrealizedPnl: number;
1478
+ offset?: number;
1495
1479
  /**
1496
- * Total realized P&L in USDC (6 decimals)
1480
+ * Pagination limit
1497
1481
  */
1498
- totalRealizedPnl: number;
1482
+ limit?: number;
1483
+ }
1484
+ /**
1485
+ * Sort options for active markets.
1486
+ * @public
1487
+ */
1488
+ type ActiveMarketsSortBy = 'lp_rewards' | 'ending_soon' | 'newest' | 'high_value' | 'liquidity';
1489
+ /**
1490
+ * Query parameters for active markets endpoint.
1491
+ * @public
1492
+ */
1493
+ interface ActiveMarketsParams {
1499
1494
  /**
1500
- * Total unrealized P&L percentage
1495
+ * Maximum number of markets to return (max 25)
1496
+ * @defaultValue 25
1501
1497
  */
1502
- totalUnrealizedPnlPercent: number;
1498
+ limit?: number;
1503
1499
  /**
1504
- * Number of open positions
1500
+ * Page number for pagination (starts at 1)
1501
+ * @defaultValue 1
1505
1502
  */
1506
- positionCount: number;
1503
+ page?: number;
1507
1504
  /**
1508
- * Number of markets with positions
1505
+ * Sort order for markets
1509
1506
  */
1510
- marketCount: number;
1507
+ sortBy?: ActiveMarketsSortBy;
1508
+ }
1509
+ /**
1510
+ * Active markets response from API.
1511
+ * @public
1512
+ */
1513
+ interface ActiveMarketsResponse {
1511
1514
  /**
1512
- * Breakdown by position type
1515
+ * Array of active markets
1513
1516
  */
1514
- breakdown: {
1515
- clob: {
1516
- positions: number;
1517
- value: number;
1518
- pnl: number;
1519
- };
1520
- amm: {
1521
- positions: number;
1522
- value: number;
1523
- pnl: number;
1524
- };
1525
- };
1517
+ data: Market$1[];
1518
+ /**
1519
+ * Total count of active markets
1520
+ */
1521
+ totalMarketsCount: number;
1526
1522
  }
1527
1523
 
1528
1524
  /**
@@ -1540,9 +1536,16 @@ interface WebSocketConfig {
1540
1536
  */
1541
1537
  url?: string;
1542
1538
  /**
1543
- * Session cookie for authentication
1539
+ * API key for authentication
1540
+ *
1541
+ * @remarks
1542
+ * **Required** for authenticated subscriptions (positions, transactions).
1543
+ * Not required for public subscriptions (market prices, orderbook).
1544
+ *
1545
+ * You can generate an API key at https://limitless.exchange
1546
+ * and the LIMITLESS_API_KEY environment variable.
1544
1547
  */
1545
- sessionCookie?: string;
1548
+ apiKey?: string;
1546
1549
  /**
1547
1550
  * Auto-reconnect on connection loss (default: true)
1548
1551
  */
@@ -1796,76 +1799,26 @@ interface WebSocketEvents {
1796
1799
  interface SubscriptionOptions {
1797
1800
  /**
1798
1801
  * Market slug to subscribe to (required for market-specific channels)
1802
+ * @deprecated Use marketSlugs (array) instead - server expects array format
1799
1803
  */
1800
1804
  marketSlug?: string;
1801
1805
  /**
1802
- * Market address to subscribe to (for AMM markets)
1803
- */
1804
- marketAddress?: string;
1805
- /**
1806
- * Additional filters
1807
- */
1808
- filters?: Record<string, any>;
1809
- }
1810
-
1811
- /**
1812
- * Message signer for authentication.
1813
- *
1814
- * @remarks
1815
- * This class handles signing messages with an Ethereum wallet and
1816
- * creating authentication headers required by the Limitless Exchange API.
1817
- *
1818
- * @public
1819
- */
1820
- declare class MessageSigner {
1821
- private wallet;
1822
- /**
1823
- * Creates a new message signer instance.
1824
- *
1825
- * @param wallet - Ethers wallet instance for signing
1826
- */
1827
- constructor(wallet: ethers.Wallet);
1828
- /**
1829
- * Creates authentication headers for API requests.
1830
- *
1831
- * @param signingMessage - Message to sign from the API
1832
- * @returns Promise resolving to signature headers
1833
- *
1834
- * @example
1835
- * ```typescript
1836
- * const signer = new MessageSigner(wallet);
1837
- * const headers = await signer.createAuthHeaders(message);
1838
- * ```
1806
+ * Market slugs to subscribe to (array format - required by server)
1839
1807
  */
1840
- createAuthHeaders(signingMessage: string): Promise<SignatureHeaders>;
1808
+ marketSlugs?: string[];
1841
1809
  /**
1842
- * Signs EIP-712 typed data.
1843
- *
1844
- * @param domain - EIP-712 domain
1845
- * @param types - EIP-712 types
1846
- * @param value - Value to sign
1847
- * @returns Promise resolving to signature string
1848
- *
1849
- * @example
1850
- * ```typescript
1851
- * const signature = await signer.signTypedData(domain, types, order);
1852
- * ```
1810
+ * Market address to subscribe to (for AMM markets)
1811
+ * @deprecated Use marketAddresses (array) instead - server expects array format
1853
1812
  */
1854
- signTypedData(domain: ethers.TypedDataDomain, types: Record<string, ethers.TypedDataField[]>, value: Record<string, any>): Promise<string>;
1813
+ marketAddress?: string;
1855
1814
  /**
1856
- * Gets the wallet address.
1857
- *
1858
- * @returns Ethereum address
1815
+ * Market addresses to subscribe to (array format - required by server)
1859
1816
  */
1860
- getAddress(): string;
1817
+ marketAddresses?: string[];
1861
1818
  /**
1862
- * Converts a string to hex format.
1863
- *
1864
- * @param text - String to convert
1865
- * @returns Hex string with 0x prefix
1866
- * @internal
1819
+ * Additional filters
1867
1820
  */
1868
- private stringToHex;
1821
+ filters?: Record<string, any>;
1869
1822
  }
1870
1823
 
1871
1824
  /**
@@ -1884,9 +1837,12 @@ interface HttpClientConfig {
1884
1837
  */
1885
1838
  timeout?: number;
1886
1839
  /**
1887
- * Session cookie for authenticated requests
1840
+ * API key for authenticated requests
1841
+ * @remarks
1842
+ * If not provided, will attempt to load from LIMITLESS_API_KEY environment variable.
1843
+ * Required for authenticated endpoints (portfolio, orders, etc.)
1888
1844
  */
1889
- sessionCookie?: string;
1845
+ apiKey?: string;
1890
1846
  /**
1891
1847
  * Optional logger for debugging
1892
1848
  * @defaultValue NoOpLogger (no logging)
@@ -1945,14 +1901,14 @@ interface HttpClientConfig {
1945
1901
  * HTTP client wrapper for Limitless Exchange API.
1946
1902
  *
1947
1903
  * @remarks
1948
- * This class provides a centralized HTTP client with cookie management,
1904
+ * This class provides a centralized HTTP client with API key authentication,
1949
1905
  * error handling, and request/response interceptors.
1950
1906
  *
1951
1907
  * @public
1952
1908
  */
1953
1909
  declare class HttpClient {
1954
1910
  private client;
1955
- private sessionCookie?;
1911
+ private apiKey?;
1956
1912
  private logger;
1957
1913
  /**
1958
1914
  * Creates a new HTTP client instance.
@@ -1966,15 +1922,15 @@ declare class HttpClient {
1966
1922
  */
1967
1923
  private setupInterceptors;
1968
1924
  /**
1969
- * Sets the session cookie for authenticated requests.
1925
+ * Sets the API key for authenticated requests.
1970
1926
  *
1971
- * @param cookie - Session cookie value
1927
+ * @param apiKey - API key value
1972
1928
  */
1973
- setSessionCookie(cookie: string): void;
1929
+ setApiKey(apiKey: string): void;
1974
1930
  /**
1975
- * Clears the session cookie.
1931
+ * Clears the API key.
1976
1932
  */
1977
- clearSessionCookie(): void;
1933
+ clearApiKey(): void;
1978
1934
  /**
1979
1935
  * Performs a GET request.
1980
1936
  *
@@ -1992,17 +1948,6 @@ declare class HttpClient {
1992
1948
  * @returns Promise resolving to the response data
1993
1949
  */
1994
1950
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
1995
- /**
1996
- * Performs a POST request and returns the full response object.
1997
- * Useful when you need access to response headers (e.g., for cookie extraction).
1998
- *
1999
- * @param url - Request URL
2000
- * @param data - Request body data
2001
- * @param config - Additional request configuration
2002
- * @returns Promise resolving to the full AxiosResponse object
2003
- * @internal
2004
- */
2005
- postWithResponse<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
2006
1951
  /**
2007
1952
  * Performs a DELETE request.
2008
1953
  *
@@ -2015,213 +1960,92 @@ declare class HttpClient {
2015
1960
  * @returns Promise resolving to the response data
2016
1961
  */
2017
1962
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
2018
- /**
2019
- * Extracts cookies from response headers.
2020
- *
2021
- * @param response - Axios response object
2022
- * @returns Object containing parsed cookies
2023
- * @internal
2024
- */
2025
- extractCookies(response: AxiosResponse): Record<string, string>;
2026
- }
2027
-
2028
- /**
2029
- * Authenticator for Limitless Exchange API.
2030
- *
2031
- * @remarks
2032
- * This class handles the complete authentication flow:
2033
- * 1. Get signing message from API
2034
- * 2. Sign message with wallet
2035
- * 3. Login and obtain session cookie
2036
- * 4. Verify authentication status
2037
- *
2038
- * @public
2039
- */
2040
- declare class Authenticator {
2041
- private httpClient;
2042
- private signer;
2043
- private logger;
2044
- /**
2045
- * Creates a new authenticator instance.
2046
- *
2047
- * @param httpClient - HTTP client for API requests
2048
- * @param signer - Message signer for wallet operations
2049
- * @param logger - Optional logger for debugging and monitoring (default: no logging)
2050
- *
2051
- * @example
2052
- * ```typescript
2053
- * // Without logging (default)
2054
- * const authenticator = new Authenticator(httpClient, signer);
2055
- *
2056
- * // With logging
2057
- * import { ConsoleLogger } from '@limitless-exchange/sdk';
2058
- * const logger = new ConsoleLogger('debug');
2059
- * const authenticator = new Authenticator(httpClient, signer, logger);
2060
- * ```
2061
- */
2062
- constructor(httpClient: HttpClient, signer: MessageSigner, logger?: ILogger);
2063
- /**
2064
- * Gets a signing message from the API.
2065
- *
2066
- * @returns Promise resolving to signing message string
2067
- * @throws Error if API request fails
2068
- *
2069
- * @example
2070
- * ```typescript
2071
- * const message = await authenticator.getSigningMessage();
2072
- * console.log(message);
2073
- * ```
2074
- */
2075
- getSigningMessage(): Promise<string>;
2076
- /**
2077
- * Authenticates with the API and obtains session cookie.
2078
- *
2079
- * @param options - Login options including client type and smart wallet
2080
- * @returns Promise resolving to authentication result
2081
- * @throws Error if authentication fails or smart wallet is required but not provided
2082
- *
2083
- * @example
2084
- * ```typescript
2085
- * // EOA authentication
2086
- * const result = await authenticator.authenticate({ client: 'eoa' });
2087
- *
2088
- * // ETHERSPOT with smart wallet
2089
- * const result = await authenticator.authenticate({
2090
- * client: 'etherspot',
2091
- * smartWallet: '0x...'
2092
- * });
2093
- * ```
2094
- */
2095
- authenticate(options?: LoginOptions): Promise<AuthResult>;
2096
- /**
2097
- * Verifies the current authentication status.
2098
- *
2099
- * @param sessionCookie - Session cookie to verify
2100
- * @returns Promise resolving to user's Ethereum address
2101
- * @throws Error if session is invalid
2102
- *
2103
- * @example
2104
- * ```typescript
2105
- * const address = await authenticator.verifyAuth(sessionCookie);
2106
- * console.log(`Authenticated as: ${address}`);
2107
- * ```
2108
- */
2109
- verifyAuth(sessionCookie: string): Promise<string>;
2110
- /**
2111
- * Logs out and clears the session.
2112
- *
2113
- * @param sessionCookie - Session cookie to invalidate
2114
- * @throws Error if logout request fails
2115
- *
2116
- * @example
2117
- * ```typescript
2118
- * await authenticator.logout(sessionCookie);
2119
- * console.log('Logged out successfully');
2120
- * ```
2121
- */
2122
- logout(sessionCookie: string): Promise<void>;
2123
1963
  }
2124
1964
 
2125
1965
  /**
2126
- * Optional helper for automatic authentication retry on token expiration.
2127
- * @module auth/authenticated-client
2128
- */
2129
-
2130
- /**
2131
- * Configuration for authenticated client with auto-retry.
2132
- * @public
1966
+ * Market class with fluent API methods.
1967
+ * @module types/market-class
2133
1968
  */
2134
- interface AuthenticatedClientConfig {
2135
- /**
2136
- * HTTP client instance
2137
- */
2138
- httpClient: HttpClient;
2139
- /**
2140
- * Authenticator instance
2141
- */
2142
- authenticator: Authenticator;
2143
- /**
2144
- * Authentication client type ('eoa' or 'etherspot')
2145
- */
2146
- client: 'eoa' | 'etherspot';
2147
- /**
2148
- * Optional smart wallet address (required for 'etherspot')
2149
- */
2150
- smartWallet?: string;
2151
- /**
2152
- * Optional logger for debugging
2153
- */
2154
- logger?: ILogger;
2155
- /**
2156
- * Maximum retry attempts for auth errors (default: 1)
2157
- */
2158
- maxRetries?: number;
2159
- }
1969
+
2160
1970
  /**
2161
- * Optional helper class that automatically re-authenticates on token expiration.
1971
+ * Market class with fluent API support.
2162
1972
  *
2163
1973
  * @remarks
2164
- * This is an optional convenience wrapper. Users can choose to handle
2165
- * authentication retry manually or use this helper for automatic retry logic.
2166
- *
2167
- * @example
2168
- * ```typescript
2169
- * // Create authenticated client with auto-retry
2170
- * const authClient = new AuthenticatedClient({
2171
- * httpClient,
2172
- * authenticator,
2173
- * client: 'eoa'
2174
- * });
2175
- *
2176
- * // Use withRetry for automatic re-authentication
2177
- * const portfolioFetcher = new PortfolioFetcher(httpClient);
2178
- * const positions = await authClient.withRetry(() =>
2179
- * portfolioFetcher.getPositions()
2180
- * );
2181
- * ```
1974
+ * This class represents a market with methods for fetching related data.
1975
+ * Instances are created by MarketFetcher and have http_client attached.
2182
1976
  *
2183
1977
  * @public
2184
1978
  */
2185
- declare class AuthenticatedClient {
2186
- private httpClient;
2187
- private authenticator;
2188
- private client;
2189
- private smartWallet?;
2190
- private logger;
2191
- private maxRetries;
1979
+ declare class Market {
1980
+ id: number;
1981
+ slug: string;
1982
+ title: string;
1983
+ proxyTitle: string | null;
1984
+ description?: string;
1985
+ collateralToken: CollateralToken;
1986
+ expirationDate: string;
1987
+ expirationTimestamp: number;
1988
+ expired?: boolean;
1989
+ createdAt: string;
1990
+ updatedAt: string;
1991
+ categories: string[];
1992
+ status: string;
1993
+ creator: MarketCreator;
1994
+ tags: string[];
1995
+ tradeType: string;
1996
+ marketType: string;
1997
+ priorityIndex: number;
1998
+ metadata: MarketMetadata;
1999
+ volume?: string;
2000
+ volumeFormatted?: string;
2001
+ conditionId?: string;
2002
+ negRiskRequestId?: string | null;
2003
+ tokens?: MarketTokens;
2004
+ prices?: number[];
2005
+ tradePrices?: TradePrices;
2006
+ isRewardable?: boolean;
2007
+ settings?: MarketSettings;
2008
+ venue?: Venue;
2009
+ logo?: string | null;
2010
+ priceOracleMetadata?: PriceOracleMetadata;
2011
+ orderInGroup?: number;
2012
+ winningOutcomeIndex?: number | null;
2013
+ outcomeTokens?: string[];
2014
+ ogImageURI?: string;
2015
+ negRiskMarketId?: string;
2016
+ markets?: Market[];
2017
+ dailyReward?: string;
2018
+ address?: string | null;
2019
+ type?: string;
2020
+ outcomes?: MarketOutcome[];
2021
+ resolutionDate?: string;
2022
+ private httpClient?;
2192
2023
  /**
2193
- * Creates a new authenticated client with auto-retry capability.
2024
+ * Creates a Market instance.
2194
2025
  *
2195
- * @param config - Configuration for authenticated client
2026
+ * @param data - Market data from API
2027
+ * @param httpClient - HTTP client for making requests
2196
2028
  */
2197
- constructor(config: AuthenticatedClientConfig);
2029
+ constructor(data: any, httpClient?: HttpClient);
2198
2030
  /**
2199
- * Executes a function with automatic retry on authentication errors.
2031
+ * Get user's orders for this market.
2200
2032
  *
2201
- * @param fn - Function to execute with auth retry
2202
- * @returns Promise resolving to the function result
2203
- * @throws Error if max retries exceeded or non-auth error occurs
2033
+ * @remarks
2034
+ * Fetches all orders placed by the authenticated user for this specific market.
2035
+ * Uses the http_client from the MarketFetcher that created this Market instance.
2036
+ *
2037
+ * @returns Promise resolving to array of user orders
2038
+ * @throws Error if market wasn't fetched via MarketFetcher
2204
2039
  *
2205
2040
  * @example
2206
2041
  * ```typescript
2207
- * // Automatic retry on 401/403
2208
- * const positions = await authClient.withRetry(() =>
2209
- * portfolioFetcher.getPositions()
2210
- * );
2211
- *
2212
- * // Works with any async operation
2213
- * const order = await authClient.withRetry(() =>
2214
- * orderClient.createOrder({ ... })
2215
- * );
2042
+ * // Clean fluent API
2043
+ * const market = await marketFetcher.getMarket("bitcoin-2024");
2044
+ * const orders = await market.getUserOrders();
2045
+ * console.log(`You have ${orders.length} orders in ${market.title}`);
2216
2046
  * ```
2217
2047
  */
2218
- withRetry<T>(fn: () => Promise<T>): Promise<T>;
2219
- /**
2220
- * Re-authenticates with the API.
2221
- *
2222
- * @internal
2223
- */
2224
- private reauthenticate;
2048
+ getUserOrders(): Promise<any[]>;
2225
2049
  }
2226
2050
 
2227
2051
  /**
@@ -2296,6 +2120,72 @@ declare class APIError extends Error {
2296
2120
  */
2297
2121
  isAuthError(): boolean;
2298
2122
  }
2123
+ /**
2124
+ * Rate limit error (HTTP 429).
2125
+ *
2126
+ * @remarks
2127
+ * Thrown when API rate limits are exceeded. The request should be retried after a delay.
2128
+ *
2129
+ * @example
2130
+ * ```typescript
2131
+ * try {
2132
+ * await marketFetcher.getActiveMarkets();
2133
+ * } catch (error) {
2134
+ * if (error instanceof RateLimitError) {
2135
+ * console.log('Rate limit exceeded, retry after delay');
2136
+ * }
2137
+ * }
2138
+ * ```
2139
+ *
2140
+ * @public
2141
+ */
2142
+ declare class RateLimitError extends APIError {
2143
+ constructor(message?: string, status?: number, data?: any, url?: string, method?: string);
2144
+ }
2145
+ /**
2146
+ * Authentication error (HTTP 401, 403).
2147
+ *
2148
+ * @remarks
2149
+ * Thrown when authentication fails or API key is invalid/missing.
2150
+ *
2151
+ * @example
2152
+ * ```typescript
2153
+ * try {
2154
+ * await portfolioFetcher.getPositions();
2155
+ * } catch (error) {
2156
+ * if (error instanceof AuthenticationError) {
2157
+ * console.log('Authentication failed - check API key');
2158
+ * }
2159
+ * }
2160
+ * ```
2161
+ *
2162
+ * @public
2163
+ */
2164
+ declare class AuthenticationError extends APIError {
2165
+ constructor(message?: string, status?: number, data?: any, url?: string, method?: string);
2166
+ }
2167
+ /**
2168
+ * Validation error (HTTP 400).
2169
+ *
2170
+ * @remarks
2171
+ * Thrown when request validation fails (invalid parameters, missing required fields, etc.).
2172
+ *
2173
+ * @example
2174
+ * ```typescript
2175
+ * try {
2176
+ * await orderClient.createOrder({ ... });
2177
+ * } catch (error) {
2178
+ * if (error instanceof ValidationError) {
2179
+ * console.log('Validation failed:', error.message);
2180
+ * }
2181
+ * }
2182
+ * ```
2183
+ *
2184
+ * @public
2185
+ */
2186
+ declare class ValidationError extends APIError {
2187
+ constructor(message: string, status?: number, data?: any, url?: string, method?: string);
2188
+ }
2299
2189
 
2300
2190
  /**
2301
2191
  * Retry mechanism for handling transient API failures.
@@ -2552,22 +2442,34 @@ declare const SIGNING_MESSAGE_TEMPLATE = "Welcome to Limitless.exchange! Please
2552
2442
  declare const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
2553
2443
  /**
2554
2444
  * Contract addresses by network
2445
+ *
2446
+ * @remarks
2447
+ * Note: CLOB and NegRisk exchange addresses are provided dynamically via the venue system
2448
+ * (market.venue.exchange and market.venue.adapter). These addresses vary per market and
2449
+ * should be fetched from the API rather than hardcoded.
2450
+ *
2555
2451
  * @public
2556
2452
  */
2557
2453
  declare const CONTRACT_ADDRESSES: {
2558
2454
  readonly 8453: {
2559
- readonly CLOB: "0xa4409D988CA2218d956BeEFD3874100F444f0DC3";
2560
- readonly NEGRISK: "0x5a38afc17F7E97ad8d6C547ddb837E40B4aEDfC6";
2455
+ readonly USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
2456
+ readonly CTF: "0xC9c98965297Bc527861c898329Ee280632B76e18";
2561
2457
  };
2562
2458
  readonly 84532: {
2563
- readonly CLOB: "0x...";
2564
- readonly NEGRISK: "0x...";
2459
+ readonly USDC: "0x...";
2460
+ readonly CTF: "0x...";
2565
2461
  };
2566
2462
  };
2567
2463
  /**
2568
- * Get contract address for a specific market type and chain
2464
+ * Get contract address for tokens (USDC or CTF)
2465
+ *
2466
+ * @remarks
2467
+ * For CLOB and NegRisk exchange addresses, use the venue system instead:
2468
+ * - Fetch market via `marketFetcher.getMarket(slug)`
2469
+ * - Use `market.venue.exchange` for signing and approvals
2470
+ * - Use `market.venue.adapter` for NegRisk adapter approvals
2569
2471
  *
2570
- * @param marketType - Market type (CLOB or NEGRISK)
2472
+ * @param contractType - Contract type (USDC or CTF)
2571
2473
  * @param chainId - Chain ID (default: 8453 for Base mainnet)
2572
2474
  * @returns Contract address
2573
2475
  *
@@ -2575,7 +2477,7 @@ declare const CONTRACT_ADDRESSES: {
2575
2477
  *
2576
2478
  * @public
2577
2479
  */
2578
- declare function getContractAddress(marketType: 'CLOB' | 'NEGRISK', chainId?: number): string;
2480
+ declare function getContractAddress(contractType: 'USDC' | 'CTF', chainId?: number): string;
2579
2481
 
2580
2482
  /**
2581
2483
  * Order builder for constructing unsigned order payloads.
@@ -2639,8 +2541,7 @@ declare class OrderBuilder {
2639
2541
  * const fokOrder = builder.buildOrder({
2640
2542
  * tokenId: '123456',
2641
2543
  * makerAmount: 50, // 50 USDC to spend
2642
- * side: Side.BUY,
2643
- * marketType: MarketType.CLOB
2544
+ * side: Side.BUY
2644
2545
  * });
2645
2546
  *
2646
2547
  * // GTC order (price + size)
@@ -2648,8 +2549,7 @@ declare class OrderBuilder {
2648
2549
  * tokenId: '123456',
2649
2550
  * price: 0.38,
2650
2551
  * size: 22.123, // Will be rounded to tick-aligned: 22.123 shares
2651
- * side: Side.BUY,
2652
- * marketType: MarketType.CLOB
2552
+ * side: Side.BUY
2653
2553
  * });
2654
2554
  * ```
2655
2555
  */
@@ -2803,8 +2703,7 @@ declare class OrderSigner {
2803
2703
  * ```typescript
2804
2704
  * const signature = await signer.signOrder(unsignedOrder, {
2805
2705
  * chainId: 8453,
2806
- * contractAddress: '0x...',
2807
- * marketType: MarketType.CLOB
2706
+ * contractAddress: '0x...'
2808
2707
  * });
2809
2708
  * ```
2810
2709
  */
@@ -2819,77 +2718,201 @@ declare class OrderSigner {
2819
2718
  */
2820
2719
  private getDomain;
2821
2720
  /**
2822
- * Gets the EIP-712 type definitions.
2721
+ * Gets the EIP-712 type definitions.
2722
+ *
2723
+ * @remarks
2724
+ * This matches the order structure expected by the Limitless Exchange
2725
+ * smart contracts.
2726
+ *
2727
+ * @returns EIP-712 types definition
2728
+ *
2729
+ * @internal
2730
+ */
2731
+ private getTypes;
2732
+ }
2733
+
2734
+ /**
2735
+ * Order validation utilities.
2736
+ * @module orders/validator
2737
+ */
2738
+
2739
+ /**
2740
+ * Order validation error class for client-side validation.
2741
+ * @public
2742
+ */
2743
+ declare class OrderValidationError extends Error {
2744
+ constructor(message: string);
2745
+ }
2746
+ /**
2747
+ * Validates order arguments before building.
2748
+ *
2749
+ * @param args - Order arguments to validate (FOK or GTC)
2750
+ * @throws OrderValidationError if validation fails
2751
+ *
2752
+ * @public
2753
+ *
2754
+ * @example
2755
+ * ```typescript
2756
+ * try {
2757
+ * validateOrderArgs(orderArgs);
2758
+ * } catch (error) {
2759
+ * console.error('Validation failed:', error.message);
2760
+ * }
2761
+ * ```
2762
+ */
2763
+ declare function validateOrderArgs(args: OrderArgs): void;
2764
+ /**
2765
+ * Validates an unsigned order.
2766
+ *
2767
+ * @param order - Unsigned order to validate
2768
+ * @throws OrderValidationError if validation fails
2769
+ *
2770
+ * @public
2771
+ *
2772
+ * @example
2773
+ * ```typescript
2774
+ * validateUnsignedOrder(unsignedOrder);
2775
+ * ```
2776
+ */
2777
+ declare function validateUnsignedOrder(order: UnsignedOrder): void;
2778
+ /**
2779
+ * Validates a signed order.
2780
+ *
2781
+ * @param order - Signed order to validate
2782
+ * @throws OrderValidationError if validation fails
2783
+ *
2784
+ * @public
2785
+ *
2786
+ * @example
2787
+ * ```typescript
2788
+ * validateSignedOrder(signedOrder);
2789
+ * ```
2790
+ */
2791
+ declare function validateSignedOrder(order: SignedOrder): void;
2792
+
2793
+ /**
2794
+ * Market data fetcher for Limitless Exchange.
2795
+ * @module markets/fetcher
2796
+ */
2797
+
2798
+ /**
2799
+ * Market data fetcher for retrieving market information and orderbooks.
2800
+ *
2801
+ * @remarks
2802
+ * This class provides methods to fetch market data, orderbooks, and prices
2803
+ * from the Limitless Exchange API.
2804
+ *
2805
+ * Venue caching: When fetching market data, venue information is automatically
2806
+ * cached for efficient order signing. This eliminates redundant API calls when
2807
+ * creating orders for the same market.
2808
+ *
2809
+ * @public
2810
+ */
2811
+ declare class MarketFetcher {
2812
+ private httpClient;
2813
+ private logger;
2814
+ private venueCache;
2815
+ /**
2816
+ * Creates a new market fetcher instance.
2817
+ *
2818
+ * @param httpClient - HTTP client for API requests
2819
+ * @param logger - Optional logger for debugging (default: no logging)
2820
+ *
2821
+ * @example
2822
+ * ```typescript
2823
+ * const fetcher = new MarketFetcher(httpClient);
2824
+ * ```
2825
+ */
2826
+ constructor(httpClient: HttpClient, logger?: ILogger);
2827
+ /**
2828
+ * Gets active markets with query parameters and pagination support.
2829
+ *
2830
+ * @param params - Query parameters for filtering and pagination
2831
+ * @returns Promise resolving to active markets response
2832
+ * @throws Error if API request fails
2833
+ *
2834
+ * @example
2835
+ * ```typescript
2836
+ * // Get 8 markets sorted by LP rewards
2837
+ * const response = await fetcher.getActiveMarkets({
2838
+ * limit: 8,
2839
+ * sortBy: 'lp_rewards'
2840
+ * });
2841
+ * console.log(`Found ${response.data.length} of ${response.totalMarketsCount} markets`);
2842
+ *
2843
+ * // Get page 2
2844
+ * const page2 = await fetcher.getActiveMarkets({
2845
+ * limit: 8,
2846
+ * page: 2,
2847
+ * sortBy: 'ending_soon'
2848
+ * });
2849
+ * ```
2850
+ */
2851
+ getActiveMarkets(params?: ActiveMarketsParams): Promise<ActiveMarketsResponse>;
2852
+ /**
2853
+ * Gets a single market by slug.
2854
+ *
2855
+ * @remarks
2856
+ * Automatically caches venue information for efficient order signing.
2857
+ * Always call this method before creating orders to ensure venue data
2858
+ * is available and avoid additional API requests.
2859
+ *
2860
+ * @param slug - Market slug identifier
2861
+ * @returns Promise resolving to market details
2862
+ * @throws Error if API request fails or market not found
2863
+ *
2864
+ * @example
2865
+ * ```typescript
2866
+ * // Get market
2867
+ * const market = await fetcher.getMarket('bitcoin-price-2024');
2868
+ * console.log(`Market: ${market.title}`);
2869
+ *
2870
+ * // Fluent API - get user orders for this market (clean!)
2871
+ * const orders = await market.getUserOrders();
2872
+ * console.log(`You have ${orders.length} orders`);
2873
+ *
2874
+ * // Venue is now cached for order signing
2875
+ * await orderClient.createOrder({
2876
+ * marketSlug: 'bitcoin-price-2024',
2877
+ * ...
2878
+ * });
2879
+ * ```
2880
+ */
2881
+ getMarket(slug: string): Promise<Market>;
2882
+ /**
2883
+ * Gets cached venue information for a market.
2823
2884
  *
2824
2885
  * @remarks
2825
- * This matches the order structure expected by the Limitless Exchange
2826
- * smart contracts.
2886
+ * Returns venue data previously cached by getMarket() call.
2887
+ * Used internally by OrderClient for efficient order signing.
2827
2888
  *
2828
- * @returns EIP-712 types definition
2889
+ * @param slug - Market slug identifier
2890
+ * @returns Cached venue information, or undefined if not in cache
2829
2891
  *
2830
- * @internal
2892
+ * @example
2893
+ * ```typescript
2894
+ * const venue = fetcher.getVenue('bitcoin-price-2024');
2895
+ * if (venue) {
2896
+ * console.log(`Exchange: ${venue.exchange}`);
2897
+ * }
2898
+ * ```
2831
2899
  */
2832
- private getTypes;
2833
- }
2834
-
2835
- /**
2836
- * Order validation utilities.
2837
- * @module orders/validator
2838
- */
2839
-
2840
- /**
2841
- * Validation error class.
2842
- * @public
2843
- */
2844
- declare class ValidationError extends Error {
2845
- constructor(message: string);
2900
+ getVenue(slug: string): Venue | undefined;
2901
+ /**
2902
+ * Gets the orderbook for a CLOB market.
2903
+ *
2904
+ * @param slug - Market slug identifier
2905
+ * @returns Promise resolving to orderbook data
2906
+ * @throws Error if API request fails
2907
+ *
2908
+ * @example
2909
+ * ```typescript
2910
+ * const orderbook = await fetcher.getOrderBook('bitcoin-price-2024');
2911
+ * console.log(`Bids: ${orderbook.bids.length}, Asks: ${orderbook.asks.length}`);
2912
+ * ```
2913
+ */
2914
+ getOrderBook(slug: string): Promise<OrderBook>;
2846
2915
  }
2847
- /**
2848
- * Validates order arguments before building.
2849
- *
2850
- * @param args - Order arguments to validate (FOK or GTC)
2851
- * @throws ValidationError if validation fails
2852
- *
2853
- * @public
2854
- *
2855
- * @example
2856
- * ```typescript
2857
- * try {
2858
- * validateOrderArgs(orderArgs);
2859
- * } catch (error) {
2860
- * console.error('Validation failed:', error.message);
2861
- * }
2862
- * ```
2863
- */
2864
- declare function validateOrderArgs(args: OrderArgs): void;
2865
- /**
2866
- * Validates an unsigned order.
2867
- *
2868
- * @param order - Unsigned order to validate
2869
- * @throws ValidationError if validation fails
2870
- *
2871
- * @public
2872
- *
2873
- * @example
2874
- * ```typescript
2875
- * validateUnsignedOrder(unsignedOrder);
2876
- * ```
2877
- */
2878
- declare function validateUnsignedOrder(order: UnsignedOrder): void;
2879
- /**
2880
- * Validates a signed order.
2881
- *
2882
- * @param order - Signed order to validate
2883
- * @throws ValidationError if validation fails
2884
- *
2885
- * @public
2886
- *
2887
- * @example
2888
- * ```typescript
2889
- * validateSignedOrder(signedOrder);
2890
- * ```
2891
- */
2892
- declare function validateSignedOrder(order: SignedOrder): void;
2893
2916
 
2894
2917
  /**
2895
2918
  * Order client for managing orders on Limitless Exchange.
@@ -2900,51 +2923,59 @@ declare function validateSignedOrder(order: SignedOrder): void;
2900
2923
  * Configuration for the order client.
2901
2924
  *
2902
2925
  * @remarks
2903
- * The order client supports two configuration modes:
2904
- * 1. Simple mode: Provide userData and marketType (auto-configures signing)
2905
- * 2. Advanced mode: Provide userData and custom signingConfig
2926
+ * The order client auto-configures signing based on venue data from the API.
2927
+ * User data (userId, feeRateBps) is automatically fetched from the profile API
2928
+ * on first order creation and cached for subsequent orders.
2929
+ *
2930
+ * Performance tip: Provide a shared marketFetcher instance to enable venue caching
2931
+ * across market fetches and order creation, avoiding redundant API calls.
2906
2932
  *
2907
2933
  * @public
2908
2934
  */
2909
2935
  interface OrderClientConfig {
2910
2936
  /**
2911
- * HTTP client for API requests
2937
+ * HTTP client for API requests (must have API key configured)
2912
2938
  */
2913
2939
  httpClient: HttpClient;
2914
2940
  /**
2915
- * Wallet for signing orders
2941
+ * Wallet for signing orders with EIP-712
2916
2942
  */
2917
2943
  wallet: ethers.Wallet;
2918
2944
  /**
2919
- * User data containing userId and feeRateBps
2945
+ * Custom signing configuration (optional)
2920
2946
  *
2921
- * @example
2922
- * ```typescript
2923
- * {
2924
- * userId: 123, // From auth result
2925
- * feeRateBps: 300 // User's fee rate (3%)
2926
- * }
2927
- * ```
2947
+ * @remarks
2948
+ * If not provided, SDK will auto-configure from venue data.
2949
+ * Useful for custom deployments or testing.
2928
2950
  */
2929
- userData: UserData;
2951
+ signingConfig?: OrderSigningConfig;
2930
2952
  /**
2931
- * Market type for auto-configuration (optional if signingConfig provided)
2953
+ * Shared MarketFetcher instance for venue caching (optional)
2932
2954
  *
2933
2955
  * @remarks
2934
- * When provided without signingConfig, automatically loads contract address
2935
- * from environment variables or SDK defaults.
2956
+ * When provided, enables efficient venue caching across market fetches and order creation.
2957
+ * If not provided, OrderClient creates its own internal MarketFetcher instance.
2936
2958
  *
2937
- * @defaultValue MarketType.CLOB
2938
- */
2939
- marketType?: MarketType;
2940
- /**
2941
- * Custom signing configuration (optional)
2959
+ * Best practice: Share the same MarketFetcher instance between market operations
2960
+ * and order creation for optimal performance.
2942
2961
  *
2943
- * @remarks
2944
- * If not provided, SDK will auto-configure based on marketType.
2945
- * Useful for custom deployments or testing.
2962
+ * @example
2963
+ * ```typescript
2964
+ * const marketFetcher = new MarketFetcher(httpClient);
2965
+ * const orderClient = new OrderClient({
2966
+ * httpClient,
2967
+ * wallet,
2968
+ * marketFetcher // Shared instance
2969
+ * });
2970
+ *
2971
+ * // Venue is cached
2972
+ * await marketFetcher.getMarket('bitcoin-2024');
2973
+ *
2974
+ * // Uses cached venue, no extra API call
2975
+ * await orderClient.createOrder({ marketSlug: 'bitcoin-2024', ... });
2976
+ * ```
2946
2977
  */
2947
- signingConfig?: OrderSigningConfig;
2978
+ marketFetcher?: MarketFetcher;
2948
2979
  /**
2949
2980
  * Optional logger
2950
2981
  */
@@ -2957,20 +2988,23 @@ interface OrderClientConfig {
2957
2988
  * This class provides high-level methods for order operations,
2958
2989
  * abstracting away HTTP details and order signing complexity.
2959
2990
  *
2991
+ * User data (userId, feeRateBps) is automatically fetched from profile API
2992
+ * on first order creation and cached for subsequent orders.
2993
+ *
2994
+ * Uses dynamic venue addressing for EIP-712 order signing. For best performance,
2995
+ * always call marketFetcher.getMarket() before creating orders to cache venue data.
2996
+ *
2960
2997
  * @example
2961
2998
  * ```typescript
2999
+ * import { ethers } from 'ethers';
3000
+ *
3001
+ * const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!);
2962
3002
  * const orderClient = new OrderClient({
2963
- * httpClient,
2964
- * wallet,
2965
- * ownerId: 123,
2966
- * feeRateBps: 100,
2967
- * signingConfig: {
2968
- * chainId: 8453,
2969
- * contractAddress: '0x...',
2970
- * marketType: MarketType.CLOB
2971
- * }
3003
+ * httpClient, // Must have API key configured
3004
+ * wallet, // For EIP-712 signing
2972
3005
  * });
2973
3006
  *
3007
+ * // User data automatically fetched on first order
2974
3008
  * const order = await orderClient.createOrder({
2975
3009
  * tokenId: '123...',
2976
3010
  * price: 0.65,
@@ -2985,42 +3019,57 @@ interface OrderClientConfig {
2985
3019
  */
2986
3020
  declare class OrderClient {
2987
3021
  private httpClient;
2988
- private orderBuilder;
3022
+ private wallet;
3023
+ private orderBuilder?;
2989
3024
  private orderSigner;
2990
- private ownerId;
3025
+ private marketFetcher;
3026
+ private cachedUserData?;
2991
3027
  private signingConfig;
2992
3028
  private logger;
2993
3029
  /**
2994
3030
  * Creates a new order client instance.
2995
3031
  *
2996
3032
  * @param config - Order client configuration
2997
- *
2998
- * @throws Error if neither marketType nor signingConfig is provided
2999
3033
  */
3000
3034
  constructor(config: OrderClientConfig);
3035
+ /**
3036
+ * Ensures user data is loaded and cached.
3037
+ * Fetches from profile API on first call, then caches for subsequent calls.
3038
+ *
3039
+ * @returns Promise resolving to cached user data
3040
+ * @internal
3041
+ */
3042
+ private ensureUserData;
3001
3043
  /**
3002
3044
  * Creates and submits a new order.
3003
3045
  *
3004
3046
  * @remarks
3005
3047
  * This method handles the complete order creation flow:
3006
- * 1. Build unsigned order
3007
- * 2. Sign with EIP-712
3008
- * 3. Submit to API
3048
+ * 1. Resolve venue address (from cache or API)
3049
+ * 2. Build unsigned order
3050
+ * 3. Sign with EIP-712 using venue.exchange as verifyingContract
3051
+ * 4. Submit to API
3052
+ *
3053
+ * Performance best practice: Always call marketFetcher.getMarket(marketSlug)
3054
+ * before createOrder() to cache venue data and avoid additional API requests.
3009
3055
  *
3010
3056
  * @param params - Order parameters
3011
3057
  * @returns Promise resolving to order response
3012
3058
  *
3013
- * @throws Error if order creation fails
3059
+ * @throws Error if order creation fails or venue not found
3014
3060
  *
3015
3061
  * @example
3016
3062
  * ```typescript
3063
+ * // Best practice: fetch market first to cache venue
3064
+ * const market = await marketFetcher.getMarket('bitcoin-2024');
3065
+ *
3017
3066
  * const order = await orderClient.createOrder({
3018
- * tokenId: '123456',
3067
+ * tokenId: market.tokens.yes,
3019
3068
  * price: 0.65,
3020
3069
  * size: 100,
3021
3070
  * side: Side.BUY,
3022
3071
  * orderType: OrderType.GTC,
3023
- * marketSlug: 'market-slug'
3072
+ * marketSlug: 'bitcoin-2024'
3024
3073
  * });
3025
3074
  *
3026
3075
  * console.log(`Order created: ${order.order.id}`);
@@ -3073,25 +3122,6 @@ declare class OrderClient {
3073
3122
  cancelAll(marketSlug: string): Promise<{
3074
3123
  message: string;
3075
3124
  }>;
3076
- /**
3077
- * @deprecated Use `cancel()` instead
3078
- */
3079
- cancelOrder(orderId: string): Promise<void>;
3080
- /**
3081
- * Gets an order by ID.
3082
- *
3083
- * @param orderId - Order ID to fetch
3084
- * @returns Promise resolving to order details
3085
- *
3086
- * @throws Error if order not found
3087
- *
3088
- * @example
3089
- * ```typescript
3090
- * const order = await orderClient.getOrder('order-id-123');
3091
- * console.log(order.order.side);
3092
- * ```
3093
- */
3094
- getOrder(orderId: string): Promise<OrderResponse>;
3095
3125
  /**
3096
3126
  * Builds an unsigned order without submitting.
3097
3127
  *
@@ -3100,11 +3130,11 @@ declare class OrderClient {
3100
3130
  * before signing and submission.
3101
3131
  *
3102
3132
  * @param params - Order parameters
3103
- * @returns Unsigned order
3133
+ * @returns Promise resolving to unsigned order
3104
3134
  *
3105
3135
  * @example
3106
3136
  * ```typescript
3107
- * const unsignedOrder = orderClient.buildUnsignedOrder({
3137
+ * const unsignedOrder = await orderClient.buildUnsignedOrder({
3108
3138
  * tokenId: '123456',
3109
3139
  * price: 0.65,
3110
3140
  * size: 100,
@@ -3112,7 +3142,7 @@ declare class OrderClient {
3112
3142
  * });
3113
3143
  * ```
3114
3144
  */
3115
- buildUnsignedOrder(params: OrderArgs): UnsignedOrder;
3145
+ buildUnsignedOrder(params: OrderArgs): Promise<UnsignedOrder>;
3116
3146
  /**
3117
3147
  * Signs an unsigned order without submitting.
3118
3148
  *
@@ -3129,104 +3159,32 @@ declare class OrderClient {
3129
3159
  * ```
3130
3160
  */
3131
3161
  signOrder(order: UnsignedOrder): Promise<string>;
3132
- }
3133
-
3134
- /**
3135
- * Market data fetcher for Limitless Exchange.
3136
- * @module markets/fetcher
3137
- */
3138
-
3139
- /**
3140
- * Market data fetcher for retrieving market information and orderbooks.
3141
- *
3142
- * @remarks
3143
- * This class provides methods to fetch market data, orderbooks, and prices
3144
- * from the Limitless Exchange API.
3145
- *
3146
- * @public
3147
- */
3148
- declare class MarketFetcher {
3149
- private httpClient;
3150
- private logger;
3151
- /**
3152
- * Creates a new market fetcher instance.
3153
- *
3154
- * @param httpClient - HTTP client for API requests
3155
- * @param logger - Optional logger for debugging (default: no logging)
3156
- *
3157
- * @example
3158
- * ```typescript
3159
- * const fetcher = new MarketFetcher(httpClient);
3160
- * ```
3161
- */
3162
- constructor(httpClient: HttpClient, logger?: ILogger);
3163
- /**
3164
- * Gets active markets with query parameters and pagination support.
3165
- *
3166
- * @param params - Query parameters for filtering and pagination
3167
- * @returns Promise resolving to active markets response
3168
- * @throws Error if API request fails
3169
- *
3170
- * @example
3171
- * ```typescript
3172
- * // Get 8 markets sorted by LP rewards
3173
- * const response = await fetcher.getActiveMarkets({
3174
- * limit: 8,
3175
- * sortBy: 'lp_rewards'
3176
- * });
3177
- * console.log(`Found ${response.data.length} of ${response.totalMarketsCount} markets`);
3178
- *
3179
- * // Get page 2
3180
- * const page2 = await fetcher.getActiveMarkets({
3181
- * limit: 8,
3182
- * page: 2,
3183
- * sortBy: 'ending_soon'
3184
- * });
3185
- * ```
3186
- */
3187
- getActiveMarkets(params?: ActiveMarketsParams): Promise<ActiveMarketsResponse>;
3188
- /**
3189
- * Gets a single market by slug.
3190
- *
3191
- * @param slug - Market slug identifier
3192
- * @returns Promise resolving to market details
3193
- * @throws Error if API request fails or market not found
3194
- *
3195
- * @example
3196
- * ```typescript
3197
- * const market = await fetcher.getMarket('bitcoin-price-2024');
3198
- * console.log(`Market: ${market.title}`);
3199
- * ```
3200
- */
3201
- getMarket(slug: string): Promise<Market>;
3202
3162
  /**
3203
- * Gets the orderbook for a CLOB market.
3163
+ * Gets the wallet address.
3204
3164
  *
3205
- * @param slug - Market slug identifier
3206
- * @returns Promise resolving to orderbook data
3207
- * @throws Error if API request fails
3165
+ * @returns Ethereum address of the wallet
3208
3166
  *
3209
3167
  * @example
3210
3168
  * ```typescript
3211
- * const orderbook = await fetcher.getOrderBook('bitcoin-price-2024');
3212
- * console.log(`Bids: ${orderbook.bids.length}, Asks: ${orderbook.asks.length}`);
3169
+ * const address = orderClient.walletAddress;
3170
+ * console.log(`Wallet: ${address}`);
3213
3171
  * ```
3214
3172
  */
3215
- getOrderBook(slug: string): Promise<OrderBook>;
3173
+ get walletAddress(): string;
3216
3174
  /**
3217
- * Gets the current price for a token.
3175
+ * Gets the owner ID (user ID from profile).
3218
3176
  *
3219
- * @param tokenId - Token ID
3220
- * @returns Promise resolving to price information
3221
- * @throws Error if API request fails
3177
+ * @returns Owner ID from user profile, or undefined if not yet loaded
3222
3178
  *
3223
3179
  * @example
3224
3180
  * ```typescript
3225
- * const price = await fetcher.getPrice('123456');
3226
- * console.log(`Current price: ${price.price}`);
3181
+ * const ownerId = orderClient.ownerId;
3182
+ * if (ownerId) {
3183
+ * console.log(`Owner ID: ${ownerId}`);
3184
+ * }
3227
3185
  * ```
3228
3186
  */
3229
- getPrice(tokenId: string): Promise<MarketPrice>;
3187
+ get ownerId(): number | undefined;
3230
3188
  }
3231
3189
 
3232
3190
  /**
@@ -3263,6 +3221,26 @@ declare class PortfolioFetcher {
3263
3221
  * ```
3264
3222
  */
3265
3223
  constructor(httpClient: HttpClient, logger?: ILogger);
3224
+ /**
3225
+ * Gets user profile for a specific wallet address.
3226
+ *
3227
+ * @remarks
3228
+ * Returns user profile data including user ID and fee rate.
3229
+ * Used internally by OrderClient to fetch user data.
3230
+ *
3231
+ * @param address - Wallet address to fetch profile for
3232
+ * @returns Promise resolving to user profile data
3233
+ * @throws Error if API request fails or user is not authenticated
3234
+ *
3235
+ * @example
3236
+ * ```typescript
3237
+ * const profile = await portfolioFetcher.getProfile('0x1234...');
3238
+ * console.log(`User ID: ${profile.id}`);
3239
+ * console.log(`Account: ${profile.account}`);
3240
+ * console.log(`Fee Rate: ${profile.rank?.feeRateBps}`);
3241
+ * ```
3242
+ */
3243
+ getProfile(address: string): Promise<any>;
3266
3244
  /**
3267
3245
  * Gets raw portfolio positions response from API.
3268
3246
  *
@@ -3309,65 +3287,32 @@ declare class PortfolioFetcher {
3309
3287
  */
3310
3288
  getAMMPositions(): Promise<AMMPosition[]>;
3311
3289
  /**
3312
- * Flattens positions into a unified format for easier consumption.
3313
- *
3314
- * @remarks
3315
- * Converts CLOB positions (which have YES/NO sides) and AMM positions
3316
- * into a unified Position array. Only includes positions with non-zero values.
3317
- *
3318
- * @returns Promise resolving to array of flattened positions
3319
- * @throws Error if API request fails
3320
- *
3321
- * @example
3322
- * ```typescript
3323
- * const positions = await portfolioFetcher.getFlattenedPositions();
3324
- * positions.forEach(pos => {
3325
- * const pnlPercent = (pos.unrealizedPnl / pos.costBasis) * 100;
3326
- * console.log(`${pos.market.title} (${pos.side}): ${pnlPercent.toFixed(2)}% P&L`);
3327
- * });
3328
- * ```
3329
- */
3330
- getFlattenedPositions(): Promise<Position[]>;
3331
- /**
3332
- * Calculates portfolio summary statistics from raw API response.
3333
- *
3334
- * @param response - Portfolio positions response from API
3335
- * @returns Portfolio summary with totals and statistics
3336
- *
3337
- * @example
3338
- * ```typescript
3339
- * const response = await portfolioFetcher.getPositions();
3340
- * const summary = portfolioFetcher.calculateSummary(response);
3290
+ * Gets paginated history of user actions.
3341
3291
  *
3342
- * console.log(`Total Portfolio Value: $${(summary.totalValue / 1e6).toFixed(2)}`);
3343
- * console.log(`Total P&L: ${summary.totalUnrealizedPnlPercent.toFixed(2)}%`);
3344
- * console.log(`CLOB Positions: ${summary.breakdown.clob.positions}`);
3345
- * console.log(`AMM Positions: ${summary.breakdown.amm.positions}`);
3346
- * ```
3347
- */
3348
- calculateSummary(response: PortfolioPositionsResponse): PortfolioSummary;
3349
- /**
3350
- * Gets positions and calculates summary in a single call.
3292
+ * Includes AMM trades, CLOB trades, Negrisk trades & conversions.
3351
3293
  *
3352
- * @returns Promise resolving to response and summary
3294
+ * @param page - Page number (starts at 1)
3295
+ * @param limit - Number of items per page
3296
+ * @returns Promise resolving to paginated history response
3353
3297
  * @throws Error if API request fails or user is not authenticated
3354
3298
  *
3355
3299
  * @example
3356
3300
  * ```typescript
3357
- * const { response, summary } = await portfolioFetcher.getPortfolio();
3358
- *
3359
- * console.log('Portfolio Summary:');
3360
- * console.log(` Total Value: $${(summary.totalValue / 1e6).toFixed(2)}`);
3361
- * console.log(` Total P&L: $${(summary.totalUnrealizedPnl / 1e6).toFixed(2)}`);
3362
- * console.log(` P&L %: ${summary.totalUnrealizedPnlPercent.toFixed(2)}%`);
3363
- * console.log(`\nCLOB Positions: ${response.clob.length}`);
3364
- * console.log(`AMM Positions: ${response.amm.length}`);
3301
+ * // Get first page
3302
+ * const response = await portfolioFetcher.getUserHistory(1, 20);
3303
+ * console.log(`Found ${response.data.length} of ${response.totalCount} entries`);
3304
+ *
3305
+ * // Process history entries
3306
+ * for (const entry of response.data) {
3307
+ * console.log(`Type: ${entry.type}`);
3308
+ * console.log(`Market: ${entry.marketSlug}`);
3309
+ * }
3310
+ *
3311
+ * // Get next page
3312
+ * const page2 = await portfolioFetcher.getUserHistory(2, 20);
3365
3313
  * ```
3366
3314
  */
3367
- getPortfolio(): Promise<{
3368
- response: PortfolioPositionsResponse;
3369
- summary: PortfolioSummary;
3370
- }>;
3315
+ getUserHistory(page?: number, limit?: number): Promise<HistoryResponse>;
3371
3316
  }
3372
3317
 
3373
3318
  /**
@@ -3382,22 +3327,36 @@ declare class PortfolioFetcher {
3382
3327
  * This client uses Socket.IO to connect to the WebSocket server and provides
3383
3328
  * typed event subscriptions for orderbook, trades, orders, and market data.
3384
3329
  *
3330
+ * **Public Subscriptions** (no authentication required):
3331
+ * - Market prices (AMM)
3332
+ * - Orderbook updates (CLOB)
3333
+ *
3334
+ * **Authenticated Subscriptions** (require API key):
3335
+ * - User positions
3336
+ * - User transactions
3337
+ *
3385
3338
  * @example
3386
3339
  * ```typescript
3387
- * // Create client
3340
+ * // Public subscription (no API key needed)
3388
3341
  * const wsClient = new WebSocketClient({
3389
- * sessionCookie: 'your-session-cookie',
3390
3342
  * autoReconnect: true,
3391
3343
  * });
3392
3344
  *
3393
- * // Subscribe to orderbook updates
3394
- * wsClient.on('orderbook', (data) => {
3395
- * console.log('Orderbook update:', data);
3345
+ * await wsClient.connect();
3346
+ * await wsClient.subscribe('subscribe_market_prices', {
3347
+ * marketSlugs: ['market-123']
3348
+ * });
3349
+ *
3350
+ * // Authenticated subscription (API key required)
3351
+ * const wsClientAuth = new WebSocketClient({
3352
+ * apiKey: process.env.LIMITLESS_API_KEY,
3353
+ * autoReconnect: true,
3396
3354
  * });
3397
3355
  *
3398
- * // Connect and subscribe
3399
- * await wsClient.connect();
3400
- * await wsClient.subscribe('orderbook', { marketSlug: 'market-123' });
3356
+ * await wsClientAuth.connect();
3357
+ * await wsClientAuth.subscribe('subscribe_positions', {
3358
+ * marketSlugs: ['market-123']
3359
+ * });
3401
3360
  * ```
3402
3361
  *
3403
3362
  * @public
@@ -3430,11 +3389,20 @@ declare class WebSocketClient {
3430
3389
  */
3431
3390
  isConnected(): boolean;
3432
3391
  /**
3433
- * Sets the session cookie for authentication.
3392
+ * Sets the API key for authentication.
3393
+ *
3394
+ * @param apiKey - API key value
3434
3395
  *
3435
- * @param sessionCookie - Session cookie value
3396
+ * @remarks
3397
+ * API key is required for authenticated subscriptions (positions, transactions).
3398
+ * If already connected, this will trigger a reconnection with the new API key.
3399
+ */
3400
+ setApiKey(apiKey: string): void;
3401
+ /**
3402
+ * Reconnects with new authentication credentials.
3403
+ * @internal
3436
3404
  */
3437
- setSessionCookie(sessionCookie: string): void;
3405
+ private reconnectWithNewAuth;
3438
3406
  /**
3439
3407
  * Connects to the WebSocket server.
3440
3408
  *
@@ -3451,24 +3419,26 @@ declare class WebSocketClient {
3451
3419
  /**
3452
3420
  * Disconnects from the WebSocket server.
3453
3421
  *
3422
+ * @returns Promise that resolves when disconnected
3423
+ *
3454
3424
  * @example
3455
3425
  * ```typescript
3456
- * wsClient.disconnect();
3426
+ * await wsClient.disconnect();
3457
3427
  * ```
3458
3428
  */
3459
- disconnect(): void;
3429
+ disconnect(): Promise<void>;
3460
3430
  /**
3461
3431
  * Subscribes to a channel.
3462
3432
  *
3463
3433
  * @param channel - Channel to subscribe to
3464
3434
  * @param options - Subscription options
3465
- * @returns Promise that resolves when subscribed
3435
+ * @returns Promise that resolves immediately (kept async for API compatibility)
3466
3436
  * @throws Error if not connected
3467
3437
  *
3468
3438
  * @example
3469
3439
  * ```typescript
3470
3440
  * // Subscribe to orderbook for a specific market
3471
- * await wsClient.subscribe('orderbook', { marketSlug: 'market-123' });
3441
+ * await wsClient.subscribe('orderbook', { marketSlugs: ['market-123'] });
3472
3442
  *
3473
3443
  * // Subscribe to all trades
3474
3444
  * await wsClient.subscribe('trades');
@@ -3484,10 +3454,11 @@ declare class WebSocketClient {
3484
3454
  * @param channel - Channel to unsubscribe from
3485
3455
  * @param options - Subscription options (must match subscribe call)
3486
3456
  * @returns Promise that resolves when unsubscribed
3457
+ * @throws Error if not connected or unsubscribe fails
3487
3458
  *
3488
3459
  * @example
3489
3460
  * ```typescript
3490
- * await wsClient.unsubscribe('orderbook', { marketSlug: 'market-123' });
3461
+ * await wsClient.unsubscribe('orderbook', { marketSlugs: ['market-123'] });
3491
3462
  * ```
3492
3463
  */
3493
3464
  unsubscribe(channel: SubscriptionChannel, options?: SubscriptionOptions): Promise<void>;
@@ -3519,10 +3490,19 @@ declare class WebSocketClient {
3519
3490
  * Removes an event listener.
3520
3491
  *
3521
3492
  * @param event - Event name
3522
- * @param handler - Event handler to remove
3493
+ * @param handler - Event handler to remove (if undefined, removes all handlers for event)
3523
3494
  * @returns This client for chaining
3495
+ *
3496
+ * @example
3497
+ * ```typescript
3498
+ * // Remove specific handler
3499
+ * wsClient.off('orderbookUpdate', myHandler);
3500
+ *
3501
+ * // Remove all handlers for event
3502
+ * wsClient.off('orderbookUpdate');
3503
+ * ```
3524
3504
  */
3525
- off<K extends keyof WebSocketEvents>(event: K, handler: WebSocketEvents[K]): this;
3505
+ off<K extends keyof WebSocketEvents>(event: K, handler?: WebSocketEvents[K]): this;
3526
3506
  /**
3527
3507
  * Attach any pending event listeners that were added before connect().
3528
3508
  * @internal
@@ -3550,4 +3530,4 @@ declare class WebSocketClient {
3550
3530
  private getChannelFromKey;
3551
3531
  }
3552
3532
 
3553
- export { type AMMPosition, APIError, type ActiveMarketsParams, type ActiveMarketsResponse, type ActiveMarketsSortBy, type AmmPriceEntry, type AuthResult, AuthenticatedClient, type AuthenticatedClientConfig, Authenticator, BASE_SEPOLIA_CHAIN_ID, type BaseOrderArgs, type CLOBPosition, CONTRACT_ADDRESSES, type ClientType, type CollateralToken, ConsoleLogger, type CreatedOrder, DEFAULT_API_URL, DEFAULT_CHAIN_ID, DEFAULT_WS_URL, type FOKOrderArgs, type FillEvent, type GTCOrderArgs, HttpClient, type HttpClientConfig, type ILogger, type LatestTrade, type LoginOptions, type Market, type MarketCreator, MarketFetcher, type MarketMetadata, type MarketOutcome, type MarketPrice, type MarketSettings, type MarketTokens, MarketType, type MarketUpdate, type MarketsResponse, MessageSigner, type ModeInfo, type NewOrderPayload, type NewPriceData, NoOpLogger, type OrderArgs, type OrderBook, OrderBuilder, OrderClient, type OrderClientConfig, type OrderMatch, type OrderResponse, OrderSigner, type OrderSigningConfig, OrderType, type OrderUpdate, type OrderbookData, type OrderbookEntry, type OrderbookUpdate, PortfolioFetcher, type PortfolioPositionsResponse, type PortfolioSummary, type Position, type PositionMarket, type PositionSide, type PriceOracleMetadata, type PriceUpdate, type ReferralData, RetryConfig, type RetryConfigOptions, RetryableClient, SIGNING_MESSAGE_TEMPLATE, Side, type SignatureHeaders, SignatureType, type SignedOrder, type SubscriptionChannel, type SubscriptionOptions, type TokenBalance, type TradeEvent, type TradePrices, type TradingMode, type TransactionEvent, type UnsignedOrder, type UserData, type UserProfile, type UserRank, ValidationError, WebSocketClient, type WebSocketConfig, type WebSocketEvents, WebSocketState, ZERO_ADDRESS, getContractAddress, retryOnErrors, validateOrderArgs, validateSignedOrder, validateUnsignedOrder, withRetry };
3533
+ export { type AMMPosition, APIError, type ActiveMarketsParams, type ActiveMarketsResponse, type ActiveMarketsSortBy, type AmmPriceEntry, AuthenticationError, BASE_SEPOLIA_CHAIN_ID, type BaseOrderArgs, type CLOBPosition, CONTRACT_ADDRESSES, type CollateralToken, ConsoleLogger, type CreatedOrder, DEFAULT_API_URL, DEFAULT_CHAIN_ID, DEFAULT_WS_URL, type FOKOrderArgs, type FillEvent, type GTCOrderArgs, type HistoryEntry, type HistoryResponse, HttpClient, type HttpClientConfig, type ILogger, type LatestTrade, Market, type MarketCreator, MarketFetcher, type Market$1 as MarketInterface, type MarketMetadata, type MarketOutcome, type MarketSettings, type MarketTokens, type MarketUpdate, type MarketsResponse, type ModeInfo, type NewOrderPayload, type NewPriceData, NoOpLogger, type OrderArgs, type OrderBook, OrderBuilder, OrderClient, type OrderClientConfig, type OrderMatch, type OrderResponse, OrderSigner, type OrderSigningConfig, OrderType, type OrderUpdate, OrderValidationError, type OrderbookData, type OrderbookEntry, type OrderbookUpdate, PortfolioFetcher, type PortfolioPositionsResponse, type PortfolioSummary, type Position, type PositionMarket, type PositionSide, type PriceOracleMetadata, type PriceUpdate, RateLimitError, type ReferralData, RetryConfig, type RetryConfigOptions, RetryableClient, SIGNING_MESSAGE_TEMPLATE, Side, SignatureType, type SignedOrder, type SubscriptionChannel, type SubscriptionOptions, type TokenBalance, type TradeEvent, type TradePrices, type TradingMode, type TransactionEvent, type UnsignedOrder, type UserData, type UserProfile, type UserRank, ValidationError, type Venue, WebSocketClient, type WebSocketConfig, type WebSocketEvents, WebSocketState, ZERO_ADDRESS, getContractAddress, retryOnErrors, validateOrderArgs, validateSignedOrder, validateUnsignedOrder, withRetry };