context-markets-react 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Context
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ <p align="center">
2
+ <img src="https://mainnet.contextcdn.com/ced823d63df9dff0390d9ad0a4e1ad3905dd199a6c50758c18a5c92a203adbd7" alt="Context" width="100%" />
3
+ </p>
4
+
5
+ <h1 align="center">Context React</h1>
6
+ <p align="center">React hooks for <a href="https://context.markets">Context Markets</a> — built on <code>context-markets</code> and TanStack Query.</p>
7
+
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/context-markets-react"><img src="https://img.shields.io/npm/v/context-markets-react" alt="npm" /></a>
10
+ <a href="https://github.com/contextwtf/context-react/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT" /></a>
11
+ <a href="https://discord.gg/RVmzZsAyM4"><img src="https://img.shields.io/badge/Discord-Join-7289da" alt="Discord" /></a>
12
+ </p>
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install context-markets-react context-markets @tanstack/react-query wagmi viem
18
+ # or
19
+ yarn add context-markets-react context-markets @tanstack/react-query wagmi viem
20
+ # or
21
+ pnpm add context-markets-react context-markets @tanstack/react-query wagmi viem
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ### 1. Wrap your app with providers
27
+
28
+ ```tsx
29
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
30
+ import { WagmiProvider } from "wagmi"
31
+ import { ContextProvider } from "context-markets-react"
32
+ import { wagmiConfig } from "./wagmi"
33
+
34
+ const queryClient = new QueryClient()
35
+
36
+ function App({ children }: { children: React.ReactNode }) {
37
+ return (
38
+ <WagmiProvider config={wagmiConfig}>
39
+ <QueryClientProvider client={queryClient}>
40
+ <ContextProvider apiKey={process.env.NEXT_PUBLIC_CONTEXT_API_KEY!}>
41
+ {children}
42
+ </ContextProvider>
43
+ </QueryClientProvider>
44
+ </WagmiProvider>
45
+ )
46
+ }
47
+ ```
48
+
49
+ ### 2. Use hooks
50
+
51
+ ```tsx
52
+ import { useMarkets, useQuotes } from "context-markets-react"
53
+
54
+ function MarketList() {
55
+ const { data, isLoading } = useMarkets({ status: "active", sortBy: "trending" })
56
+
57
+ if (isLoading) return <div>Loading...</div>
58
+
59
+ return (
60
+ <ul>
61
+ {data?.markets.map((m) => (
62
+ <li key={m.id}>{m.question}</li>
63
+ ))}
64
+ </ul>
65
+ )
66
+ }
67
+ ```
68
+
69
+ ## Available Hooks
70
+
71
+ **Markets** — `useMarkets` · `useSearchMarkets` · `useMarket` · `useOrderbook` · `useQuotes` · `usePriceHistory` · `useMarketActivity` · `useSimulateTrade` · `useOracle` · `useLatestOracleQuote`
72
+
73
+ **Orders** — `useOrders` · `useOrder` · `useCreateOrder` · `useCreateMarketOrder` · `useCancelOrder` · `useCancelReplace`
74
+
75
+ **Portfolio** — `usePortfolio` · `usePositions` · `useBalance` · `useClaimable` · `usePortfolioStats`
76
+
77
+ **Account** — `useAccountStatus` · `useAccountSetup` · `useDeposit` · `useWithdraw`
78
+
79
+ **Questions** — `useSubmitQuestion` · `useSubmitAndWait` · `useCreateMarket` · `useAgentSubmit` · `useAgentSubmitAndWait`
80
+
81
+ **Utilities** — `ContextProvider` · `useContextClient` · `contextKeys` · `ContextWalletError`
82
+
83
+ ## Peer Dependencies
84
+
85
+ `react` >= 18 · `@tanstack/react-query` >= 5 · `wagmi` >= 2 · `viem` >= 2 · `context-markets` >= 0.4
86
+
87
+ ## Documentation
88
+
89
+ - **[React SDK Guide](https://docs.context.markets/agents/react-sdk)** — setup, providers, and first component
90
+ - **[Hooks Reference](https://docs.context.markets/agents/react-sdk/hooks-reference)** — full list of hooks and parameters
91
+ - **[Best Practices](https://docs.context.markets/agents/react-sdk/best-practices)** — patterns, error handling, and tips
92
+
93
+ ## Ecosystem
94
+
95
+ | Package | Description |
96
+ |---------|-------------|
97
+ | **[context-markets](https://github.com/contextwtf/context-sdk)** | TypeScript SDK for trading |
98
+ | **[context-markets-react](https://github.com/contextwtf/context-react)** | React hooks for market data and trading |
99
+ | **[@contextwtf/mcp](https://github.com/contextwtf/context-mcp)** | MCP server for AI agents |
100
+ | **[@contextwtf/cli](https://github.com/contextwtf/context-cli)** | CLI for trading from the terminal |
101
+ | **[context-skills](https://github.com/contextwtf/context-skills)** | AI agent skill files |
102
+ | **[context-plugin](https://github.com/contextwtf/context-plugin)** | Claude Code plugin |
103
+
104
+ ## License
105
+
106
+ MIT — see [LICENSE](./LICENSE) for details.
@@ -0,0 +1,321 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+ import * as context_markets from 'context-markets';
4
+ import { ContextClient, Balance, ClaimableResponse, GetPortfolioParams, Portfolio, PortfolioStats, GetPositionsParams, PositionList, OracleQuoteLatest, Market, GetActivityParams, ActivityResponse, SearchMarketsParams, MarketList, GetOrderbookParams, Orderbook, GetPriceHistoryParams, PriceHistory, Quotes, MarketSearchParams, MarketSearchResult, SimulateTradeParams, SimulateResult, GaslessOperatorResult, WalletSetupResult, WalletStatus, GaslessDepositResult, Order, GetOrdersParams, OrderList, CancelResult, CancelReplaceResult, PlaceOrderRequest, CreateOrderResult, PlaceMarketOrderRequest, SubmitQuestionResult, AgentSubmitMarketDraft, QuestionSubmission, SubmitAndWaitOptions, CreateMarketResult } from 'context-markets';
5
+ import * as _tanstack_react_query from '@tanstack/react-query';
6
+ import { UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
7
+ import { Address, Hex } from 'viem';
8
+
9
+ interface ContextProviderProps {
10
+ apiKey: string;
11
+ rpcUrl?: string;
12
+ baseUrl?: string;
13
+ children: ReactNode;
14
+ }
15
+ declare function ContextProvider({ apiKey, rpcUrl, baseUrl, children, }: ContextProviderProps): react_jsx_runtime.JSX.Element;
16
+ declare function useContextClient(): ContextClient;
17
+
18
+ declare const contextKeys: {
19
+ readonly markets: {
20
+ readonly all: readonly ["context", "markets"];
21
+ readonly list: (params?: Record<string, unknown>) => readonly ["context", "markets", "list", Record<string, unknown>] | readonly ["context", "markets", "list"];
22
+ readonly search: (q: string, params?: Record<string, unknown>) => readonly ["context", "markets", "search", string, Record<string, unknown>] | readonly ["context", "markets", "search", string];
23
+ readonly get: (id: string) => readonly ["context", "markets", "get", string];
24
+ readonly orderbook: (id: string, params?: Record<string, unknown>) => readonly ["context", "markets", "orderbook", string, Record<string, unknown>] | readonly ["context", "markets", "orderbook", string];
25
+ readonly quotes: (id: string) => readonly ["context", "markets", "quotes", string];
26
+ readonly priceHistory: (id: string, params?: Record<string, unknown>) => readonly ["context", "markets", "priceHistory", string, Record<string, unknown>] | readonly ["context", "markets", "priceHistory", string];
27
+ readonly activity: (id: string, params?: Record<string, unknown>) => readonly ["context", "markets", "activity", string, Record<string, unknown>] | readonly ["context", "markets", "activity", string];
28
+ readonly simulate: (params: Record<string, unknown>) => readonly ["context", "markets", "simulate", Record<string, unknown>];
29
+ readonly oracle: (id: string) => readonly ["context", "markets", "oracle", string];
30
+ readonly latestOracleQuote: (id: string) => readonly ["context", "markets", "latestOracleQuote", string];
31
+ };
32
+ readonly orders: {
33
+ readonly all: readonly ["context", "orders"];
34
+ readonly list: (params?: Record<string, unknown>) => readonly ["context", "orders", "list", Record<string, unknown>] | readonly ["context", "orders", "list"];
35
+ readonly get: (id: string) => readonly ["context", "orders", "get", string];
36
+ };
37
+ readonly portfolio: {
38
+ readonly all: readonly ["context", "portfolio"];
39
+ readonly get: (address?: string, params?: Record<string, unknown>) => readonly ["context", "portfolio", "get", string, ...Record<string, unknown>[]] | readonly ["context", "portfolio", "get"];
40
+ readonly balance: (address?: string) => readonly ["context", "portfolio", "balance", string] | readonly ["context", "portfolio", "balance"];
41
+ readonly claimable: (address?: string) => readonly ["context", "portfolio", "claimable", string] | readonly ["context", "portfolio", "claimable"];
42
+ readonly stats: (address?: string) => readonly ["context", "portfolio", "stats", string] | readonly ["context", "portfolio", "stats"];
43
+ readonly positions: (address?: string, params?: Record<string, unknown>) => readonly ["context", "portfolio", "positions", string, ...Record<string, unknown>[]] | readonly ["context", "portfolio", "positions"];
44
+ };
45
+ readonly account: {
46
+ readonly all: readonly ["context", "account"];
47
+ readonly status: () => readonly ["context", "account", "status"];
48
+ };
49
+ };
50
+
51
+ declare class ContextWalletError extends Error {
52
+ name: string;
53
+ constructor(hookName: string);
54
+ }
55
+
56
+ declare function usePortfolio(address?: Address, params?: GetPortfolioParams, options?: Omit<UseQueryOptions<Portfolio>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
57
+ portfolio: context_markets.ApiComponents["schemas"]["Position"][];
58
+ marketIds: string[];
59
+ cursor: string | null;
60
+ }, Error>;
61
+ declare function useBalance(address?: Address, options?: Omit<UseQueryOptions<Balance>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
62
+ address: string;
63
+ usdc: {
64
+ tokenAddress: string;
65
+ balance: string;
66
+ settlementBalance: string;
67
+ walletBalance: string;
68
+ };
69
+ outcomeTokens: context_markets.ApiComponents["schemas"]["OutcomeTokenBalance"][];
70
+ }, Error>;
71
+ declare function useClaimable(address?: Address, options?: Omit<UseQueryOptions<ClaimableResponse>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
72
+ positions: context_markets.ApiComponents["schemas"]["ClaimablePosition"][];
73
+ markets: context_markets.ApiComponents["schemas"]["ClaimableMarket"][];
74
+ totalClaimable: string;
75
+ }, Error>;
76
+ declare function usePortfolioStats(address?: Address, options?: Omit<UseQueryOptions<PortfolioStats>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
77
+ currentPortfolioValue: string;
78
+ currentPortfolioPercentChange: number;
79
+ predictionsPlaced: number;
80
+ totalPlaced: string;
81
+ allTimeWinLoss: string;
82
+ allTimeReturnPct: number;
83
+ }, Error>;
84
+ declare function usePositions(address?: Address, params?: GetPositionsParams, options?: Omit<UseQueryOptions<PositionList>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
85
+ positions: context_markets.ApiComponents["schemas"]["PortfolioPosition"][];
86
+ cursor: string | null;
87
+ }, Error>;
88
+
89
+ declare function useMarkets(params?: SearchMarketsParams, options?: Omit<UseQueryOptions<MarketList>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
90
+ markets: context_markets.ApiComponents["schemas"]["Market"][];
91
+ cursor: string | null;
92
+ }, Error>;
93
+ declare function useSearchMarkets(params: MarketSearchParams, options?: Omit<UseQueryOptions<MarketSearchResult>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<MarketSearchResult, Error>;
94
+ declare function useMarket(marketId: string, options?: Omit<UseQueryOptions<Market>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
95
+ id: string;
96
+ oracle: string;
97
+ question: string;
98
+ questionSubmissionId?: string | null;
99
+ shortQuestion: string;
100
+ outcomeTokens: string[];
101
+ outcomePrices: context_markets.ApiComponents["schemas"]["OutcomePrice"][];
102
+ creator: string;
103
+ creatorProfile: {
104
+ username: string | null;
105
+ avatarUrl: string | null;
106
+ } | null;
107
+ blockTime: string;
108
+ chainId: string;
109
+ txHash: string;
110
+ volume: string;
111
+ volume24h: string;
112
+ participantCount: number;
113
+ executableAt: string | null;
114
+ proposedAt: string | null;
115
+ resolvedAt: string | null;
116
+ payoutPcts: number[] | null;
117
+ resolutionStatus: "none" | "pending" | "resolved";
118
+ metadata: context_markets.ApiComponents["schemas"]["MarketMetadata"];
119
+ resolutionCriteria: string;
120
+ deadline: string;
121
+ status: "active" | "pending" | "resolved" | "closed";
122
+ createdAt: string;
123
+ outcome: number | null;
124
+ contractAddress: string;
125
+ }, Error>;
126
+ declare function useOrderbook(marketId: string, params?: GetOrderbookParams, options?: Omit<UseQueryOptions<Orderbook>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
127
+ marketId: string;
128
+ bids: {
129
+ price: number;
130
+ size: number;
131
+ }[];
132
+ asks: {
133
+ price: number;
134
+ size: number;
135
+ }[];
136
+ timestamp: string;
137
+ }, Error>;
138
+ declare function useQuotes(marketId: string, options?: Omit<UseQueryOptions<Quotes>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
139
+ marketId: string;
140
+ yes: {
141
+ bid: number | null;
142
+ ask: number | null;
143
+ last: number | null;
144
+ };
145
+ no: {
146
+ bid: number | null;
147
+ ask: number | null;
148
+ last: number | null;
149
+ };
150
+ spread: number | null;
151
+ timestamp: string;
152
+ }, Error>;
153
+ declare function usePriceHistory(marketId: string, params?: GetPriceHistoryParams, options?: Omit<UseQueryOptions<PriceHistory>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
154
+ prices: {
155
+ time: number;
156
+ price: number;
157
+ }[];
158
+ startTime: number;
159
+ endTime: number;
160
+ interval: number;
161
+ }, Error>;
162
+ declare function useMarketActivity(marketId: string, params?: GetActivityParams, options?: Omit<UseQueryOptions<ActivityResponse>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
163
+ marketId?: string;
164
+ activity: context_markets.ApiComponents["schemas"]["ActivityItem"][];
165
+ pagination: context_markets.ApiComponents["schemas"]["Pagination"];
166
+ }, Error>;
167
+ declare function useSimulateTrade(marketId: string, params: SimulateTradeParams, options?: Omit<UseQueryOptions<SimulateResult>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
168
+ marketId: string;
169
+ side: "yes" | "no";
170
+ amount: number;
171
+ amountType: "usd" | "contracts";
172
+ estimatedContracts: number;
173
+ estimatedAvgPrice: number;
174
+ estimatedSlippage: number;
175
+ warnings: context_markets.ApiComponents["schemas"]["SimulateWarning"][];
176
+ }, Error>;
177
+ declare function useOracle(marketId: string, options?: Omit<UseQueryOptions<any>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<any, Error>;
178
+ declare function useLatestOracleQuote(marketId: string, options?: Omit<UseQueryOptions<OracleQuoteLatest>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
179
+ quote: context_markets.ApiComponents["schemas"]["OracleQuote"] & unknown;
180
+ }, Error>;
181
+
182
+ declare function useAccountStatus(options?: Omit<UseQueryOptions<WalletStatus>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<WalletStatus, Error>;
183
+ declare function useAccountSetup(options?: Omit<UseMutationOptions<GaslessOperatorResult | WalletSetupResult, Error, void>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
184
+ success: true;
185
+ txHash: string;
186
+ user: string;
187
+ operator: string;
188
+ relayer: string;
189
+ } | WalletSetupResult, Error, void, unknown>;
190
+ declare function useDeposit(options?: Omit<UseMutationOptions<GaslessDepositResult | Hex, Error, number>, "mutationFn">): _tanstack_react_query.UseMutationResult<`0x${string}` | {
191
+ success: true;
192
+ txHash: string;
193
+ user: string;
194
+ token: string;
195
+ amount: string;
196
+ relayer: string;
197
+ }, Error, number, unknown>;
198
+ declare function useWithdraw(options?: Omit<UseMutationOptions<Hex, Error, number>, "mutationFn">): _tanstack_react_query.UseMutationResult<`0x${string}`, Error, number, unknown>;
199
+
200
+ declare function useOrders(params?: GetOrdersParams, options?: Omit<UseQueryOptions<OrderList>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
201
+ orders: context_markets.ApiComponents["schemas"]["OrderWithAvgFillPrice"][];
202
+ markets: {
203
+ [key: string]: context_markets.ApiComponents["schemas"]["OrderMarketInfo"];
204
+ };
205
+ cursor: string | null;
206
+ }, Error>;
207
+ declare function useOrder(orderId: string, options?: Omit<UseQueryOptions<Order>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<{
208
+ marketId: string;
209
+ trader: string;
210
+ nonce: string;
211
+ side: 0 | 1;
212
+ price: string;
213
+ size: string;
214
+ filledSize: string;
215
+ remainingSize: string;
216
+ percentFilled: number;
217
+ insertedAt: string;
218
+ type: "limit" | "market";
219
+ status: "open" | "filled" | "cancelled" | "expired" | "voided";
220
+ voidedAt: string | null;
221
+ voidReason: "UNFILLED_MARKET_ORDER" | "UNDER_COLLATERALIZED" | "MISSING_OPERATOR_APPROVAL" | "BELOW_MIN_FILL_SIZE" | "INVALID_SIGNATURE" | "MARKET_RESOLVED" | "ADMIN_VOID" | null;
222
+ outcomeIndex: number;
223
+ }, Error>;
224
+
225
+ declare function useCreateOrder(options?: Omit<UseMutationOptions<CreateOrderResult, Error, PlaceOrderRequest>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
226
+ success: true;
227
+ order: context_markets.ApiComponents["schemas"]["Order"];
228
+ }, Error, PlaceOrderRequest, unknown>;
229
+ declare function useCreateMarketOrder(options?: Omit<UseMutationOptions<CreateOrderResult, Error, PlaceMarketOrderRequest>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
230
+ success: true;
231
+ order: context_markets.ApiComponents["schemas"]["Order"];
232
+ }, Error, PlaceMarketOrderRequest, unknown>;
233
+ declare function useCancelOrder(options?: Omit<UseMutationOptions<CancelResult, Error, Hex>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
234
+ success: boolean;
235
+ alreadyCancelled: boolean;
236
+ }, Error, `0x${string}`, unknown>;
237
+ declare function useCancelReplace(options?: Omit<UseMutationOptions<CancelReplaceResult, Error, {
238
+ cancelNonce: Hex;
239
+ newOrder: PlaceOrderRequest;
240
+ }>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
241
+ cancel: context_markets.ApiComponents["schemas"]["CancelDetail"];
242
+ create: context_markets.ApiComponents["schemas"]["OrderCreated"];
243
+ }, Error, {
244
+ cancelNonce: Hex;
245
+ newOrder: PlaceOrderRequest;
246
+ }, unknown>;
247
+
248
+ declare function useSubmitQuestion(options?: Omit<UseMutationOptions<SubmitQuestionResult, Error, string>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
249
+ submissionId: string;
250
+ questions: unknown[];
251
+ accounts: {
252
+ [key: string]: unknown;
253
+ };
254
+ qualityExplanation: string | null;
255
+ refuseToResolve: boolean;
256
+ status: string;
257
+ statusUpdates: unknown[];
258
+ pollUrl: string;
259
+ }, Error, string, unknown>;
260
+ interface SubmitAndWaitInput {
261
+ question: string;
262
+ options?: SubmitAndWaitOptions;
263
+ }
264
+ declare function useSubmitAndWait(options?: Omit<UseMutationOptions<QuestionSubmission, Error, SubmitAndWaitInput>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
265
+ questions: context_markets.ApiComponents["schemas"]["SubmissionQuestion"][];
266
+ accounts: {
267
+ [key: string]: context_markets.ApiComponents["schemas"]["SubmissionAccount"];
268
+ };
269
+ qualityExplanation: string | null;
270
+ refuseToResolve: boolean;
271
+ similarMarkets?: context_markets.ApiComponents["schemas"]["SimilarMarket"][];
272
+ rejectionReasons?: context_markets.ApiComponents["schemas"]["RejectionReason"][];
273
+ appliedChanges?: string[];
274
+ submissionId?: string;
275
+ status: string;
276
+ statusUpdates: {
277
+ tool: string;
278
+ status: string;
279
+ timestamp: string;
280
+ }[];
281
+ }, Error, SubmitAndWaitInput, unknown>;
282
+ declare function useCreateMarket(options?: Omit<UseMutationOptions<CreateMarketResult, Error, string>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
283
+ marketId: string;
284
+ txHash: string;
285
+ }, Error, string, unknown>;
286
+ declare function useAgentSubmit(options?: Omit<UseMutationOptions<SubmitQuestionResult, Error, AgentSubmitMarketDraft>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
287
+ submissionId: string;
288
+ questions: unknown[];
289
+ accounts: {
290
+ [key: string]: unknown;
291
+ };
292
+ qualityExplanation: string | null;
293
+ refuseToResolve: boolean;
294
+ status: string;
295
+ statusUpdates: unknown[];
296
+ pollUrl: string;
297
+ }, Error, AgentSubmitMarketDraft, unknown>;
298
+ interface AgentSubmitAndWaitInput {
299
+ draft: AgentSubmitMarketDraft;
300
+ options?: SubmitAndWaitOptions;
301
+ }
302
+ declare function useAgentSubmitAndWait(options?: Omit<UseMutationOptions<QuestionSubmission, Error, AgentSubmitAndWaitInput>, "mutationFn">): _tanstack_react_query.UseMutationResult<{
303
+ questions: context_markets.ApiComponents["schemas"]["SubmissionQuestion"][];
304
+ accounts: {
305
+ [key: string]: context_markets.ApiComponents["schemas"]["SubmissionAccount"];
306
+ };
307
+ qualityExplanation: string | null;
308
+ refuseToResolve: boolean;
309
+ similarMarkets?: context_markets.ApiComponents["schemas"]["SimilarMarket"][];
310
+ rejectionReasons?: context_markets.ApiComponents["schemas"]["RejectionReason"][];
311
+ appliedChanges?: string[];
312
+ submissionId?: string;
313
+ status: string;
314
+ statusUpdates: {
315
+ tool: string;
316
+ status: string;
317
+ timestamp: string;
318
+ }[];
319
+ }, Error, AgentSubmitAndWaitInput, unknown>;
320
+
321
+ export { ContextProvider, ContextWalletError, contextKeys, useAccountSetup, useAccountStatus, useAgentSubmit, useAgentSubmitAndWait, useBalance, useCancelOrder, useCancelReplace, useClaimable, useContextClient, useCreateMarket, useCreateMarketOrder, useCreateOrder, useDeposit, useLatestOracleQuote, useMarket, useMarketActivity, useMarkets, useOracle, useOrder, useOrderbook, useOrders, usePortfolio, usePortfolioStats, usePositions, usePriceHistory, useQuotes, useSearchMarkets, useSimulateTrade, useSubmitAndWait, useSubmitQuestion, useWithdraw };
package/dist/index.js ADDED
@@ -0,0 +1,459 @@
1
+ // src/provider.tsx
2
+ import {
3
+ createContext,
4
+ useContext,
5
+ useMemo
6
+ } from "react";
7
+ import { ContextClient } from "context-markets";
8
+ import { useWalletClient, useAccount } from "wagmi";
9
+ import { jsx } from "react/jsx-runtime";
10
+ var ContextClientContext = createContext(null);
11
+ function ContextProvider({
12
+ apiKey,
13
+ rpcUrl,
14
+ baseUrl,
15
+ children
16
+ }) {
17
+ const { data: walletClient } = useWalletClient();
18
+ const { address } = useAccount();
19
+ const client = useMemo(() => {
20
+ return new ContextClient({
21
+ apiKey,
22
+ rpcUrl,
23
+ baseUrl,
24
+ ...walletClient ? { signer: { walletClient } } : {}
25
+ });
26
+ }, [apiKey, rpcUrl, baseUrl, walletClient, address]);
27
+ return /* @__PURE__ */ jsx(ContextClientContext.Provider, { value: client, children });
28
+ }
29
+ function useContextClient() {
30
+ const client = useContext(ContextClientContext);
31
+ if (!client) {
32
+ throw new Error(
33
+ "useContextClient must be used within a <ContextProvider>"
34
+ );
35
+ }
36
+ return client;
37
+ }
38
+
39
+ // src/query-keys.ts
40
+ var PREFIX = "context";
41
+ var contextKeys = {
42
+ markets: {
43
+ all: [PREFIX, "markets"],
44
+ list: (params) => params ? [PREFIX, "markets", "list", params] : [PREFIX, "markets", "list"],
45
+ search: (q, params) => params ? [PREFIX, "markets", "search", q, params] : [PREFIX, "markets", "search", q],
46
+ get: (id) => [PREFIX, "markets", "get", id],
47
+ orderbook: (id, params) => params ? [PREFIX, "markets", "orderbook", id, params] : [PREFIX, "markets", "orderbook", id],
48
+ quotes: (id) => [PREFIX, "markets", "quotes", id],
49
+ priceHistory: (id, params) => params ? [PREFIX, "markets", "priceHistory", id, params] : [PREFIX, "markets", "priceHistory", id],
50
+ activity: (id, params) => params ? [PREFIX, "markets", "activity", id, params] : [PREFIX, "markets", "activity", id],
51
+ simulate: (params) => [PREFIX, "markets", "simulate", params],
52
+ oracle: (id) => [PREFIX, "markets", "oracle", id],
53
+ latestOracleQuote: (id) => [PREFIX, "markets", "latestOracleQuote", id]
54
+ },
55
+ orders: {
56
+ all: [PREFIX, "orders"],
57
+ list: (params) => params ? [PREFIX, "orders", "list", params] : [PREFIX, "orders", "list"],
58
+ get: (id) => [PREFIX, "orders", "get", id]
59
+ },
60
+ portfolio: {
61
+ all: [PREFIX, "portfolio"],
62
+ get: (address, params) => address ? [PREFIX, "portfolio", "get", address, ...params ? [params] : []] : [PREFIX, "portfolio", "get"],
63
+ balance: (address) => address ? [PREFIX, "portfolio", "balance", address] : [PREFIX, "portfolio", "balance"],
64
+ claimable: (address) => address ? [PREFIX, "portfolio", "claimable", address] : [PREFIX, "portfolio", "claimable"],
65
+ stats: (address) => address ? [PREFIX, "portfolio", "stats", address] : [PREFIX, "portfolio", "stats"],
66
+ positions: (address, params) => address ? [PREFIX, "portfolio", "positions", address, ...params ? [params] : []] : [PREFIX, "portfolio", "positions"]
67
+ },
68
+ account: {
69
+ all: [PREFIX, "account"],
70
+ status: () => [PREFIX, "account", "status"]
71
+ }
72
+ };
73
+
74
+ // src/errors.ts
75
+ var ContextWalletError = class extends Error {
76
+ constructor(hookName) {
77
+ super(
78
+ `Wallet not connected. Connect a wallet before calling ${hookName}().`
79
+ );
80
+ this.name = "ContextWalletError";
81
+ }
82
+ };
83
+
84
+ // src/hooks/usePortfolio.ts
85
+ import { useQuery } from "@tanstack/react-query";
86
+ function usePortfolio(address, params, options) {
87
+ const client = useContextClient();
88
+ return useQuery({
89
+ queryKey: contextKeys.portfolio.get(address, params),
90
+ queryFn: () => client.portfolio.get(address, params),
91
+ ...options
92
+ });
93
+ }
94
+ function useBalance(address, options) {
95
+ const client = useContextClient();
96
+ return useQuery({
97
+ queryKey: contextKeys.portfolio.balance(address),
98
+ queryFn: () => client.portfolio.balance(address),
99
+ ...options
100
+ });
101
+ }
102
+ function useClaimable(address, options) {
103
+ const client = useContextClient();
104
+ return useQuery({
105
+ queryKey: contextKeys.portfolio.claimable(address),
106
+ queryFn: () => client.portfolio.claimable(address),
107
+ ...options
108
+ });
109
+ }
110
+ function usePortfolioStats(address, options) {
111
+ const client = useContextClient();
112
+ return useQuery({
113
+ queryKey: contextKeys.portfolio.stats(address),
114
+ queryFn: () => client.portfolio.stats(address),
115
+ ...options
116
+ });
117
+ }
118
+ function usePositions(address, params, options) {
119
+ const client = useContextClient();
120
+ return useQuery({
121
+ queryKey: contextKeys.portfolio.positions(address, params),
122
+ queryFn: () => client.portfolio.positions(address, params),
123
+ ...options
124
+ });
125
+ }
126
+
127
+ // src/hooks/useMarkets.ts
128
+ import { useQuery as useQuery2 } from "@tanstack/react-query";
129
+ function useMarkets(params, options) {
130
+ const client = useContextClient();
131
+ return useQuery2({
132
+ queryKey: contextKeys.markets.list(params),
133
+ queryFn: () => client.markets.list(params),
134
+ ...options
135
+ });
136
+ }
137
+ function useSearchMarkets(params, options) {
138
+ const client = useContextClient();
139
+ return useQuery2({
140
+ queryKey: contextKeys.markets.search(params.q, params),
141
+ queryFn: () => client.markets.search(params),
142
+ enabled: !!params.q,
143
+ ...options
144
+ });
145
+ }
146
+ function useMarket(marketId, options) {
147
+ const client = useContextClient();
148
+ return useQuery2({
149
+ queryKey: contextKeys.markets.get(marketId),
150
+ queryFn: () => client.markets.get(marketId),
151
+ enabled: !!marketId,
152
+ ...options
153
+ });
154
+ }
155
+ function useOrderbook(marketId, params, options) {
156
+ const client = useContextClient();
157
+ return useQuery2({
158
+ queryKey: contextKeys.markets.orderbook(marketId, params),
159
+ queryFn: () => client.markets.orderbook(marketId, params),
160
+ enabled: !!marketId,
161
+ ...options
162
+ });
163
+ }
164
+ function useQuotes(marketId, options) {
165
+ const client = useContextClient();
166
+ return useQuery2({
167
+ queryKey: contextKeys.markets.quotes(marketId),
168
+ queryFn: () => client.markets.quotes(marketId),
169
+ enabled: !!marketId,
170
+ ...options
171
+ });
172
+ }
173
+ function usePriceHistory(marketId, params, options) {
174
+ const client = useContextClient();
175
+ return useQuery2({
176
+ queryKey: contextKeys.markets.priceHistory(marketId, params),
177
+ queryFn: () => client.markets.priceHistory(marketId, params),
178
+ enabled: !!marketId,
179
+ ...options
180
+ });
181
+ }
182
+ function useMarketActivity(marketId, params, options) {
183
+ const client = useContextClient();
184
+ return useQuery2({
185
+ queryKey: contextKeys.markets.activity(marketId, params),
186
+ queryFn: () => client.markets.activity(marketId, params),
187
+ enabled: !!marketId,
188
+ ...options
189
+ });
190
+ }
191
+ function useSimulateTrade(marketId, params, options) {
192
+ const client = useContextClient();
193
+ return useQuery2({
194
+ queryKey: contextKeys.markets.simulate({ marketId, ...params }),
195
+ queryFn: () => client.markets.simulate(marketId, params),
196
+ enabled: !!marketId,
197
+ ...options
198
+ });
199
+ }
200
+ function useOracle(marketId, options) {
201
+ const client = useContextClient();
202
+ return useQuery2({
203
+ queryKey: contextKeys.markets.oracle(marketId),
204
+ queryFn: () => client.markets.oracle(marketId),
205
+ enabled: !!marketId,
206
+ ...options
207
+ });
208
+ }
209
+ function useLatestOracleQuote(marketId, options) {
210
+ const client = useContextClient();
211
+ return useQuery2({
212
+ queryKey: contextKeys.markets.latestOracleQuote(marketId),
213
+ queryFn: () => client.markets.latestOracleQuote(marketId),
214
+ enabled: !!marketId,
215
+ ...options
216
+ });
217
+ }
218
+
219
+ // src/hooks/useAccount.ts
220
+ import {
221
+ useQuery as useQuery3,
222
+ useMutation,
223
+ useQueryClient
224
+ } from "@tanstack/react-query";
225
+ function useAccountStatus(options) {
226
+ const client = useContextClient();
227
+ return useQuery3({
228
+ queryKey: contextKeys.account.status(),
229
+ queryFn: () => client.account.status(),
230
+ ...options
231
+ });
232
+ }
233
+ function useAccountSetup(options) {
234
+ const client = useContextClient();
235
+ const queryClient = useQueryClient();
236
+ return useMutation({
237
+ mutationFn: async () => {
238
+ try {
239
+ return await client.account.gaslessSetup();
240
+ } catch {
241
+ return await client.account.setup();
242
+ }
243
+ },
244
+ retry: false,
245
+ onSuccess: (...args) => {
246
+ queryClient.invalidateQueries({ queryKey: contextKeys.account.all });
247
+ options?.onSuccess?.(...args);
248
+ },
249
+ ...options
250
+ });
251
+ }
252
+ function useDeposit(options) {
253
+ const client = useContextClient();
254
+ const queryClient = useQueryClient();
255
+ return useMutation({
256
+ mutationFn: async (amount) => {
257
+ try {
258
+ return await client.account.gaslessDeposit(amount);
259
+ } catch {
260
+ return await client.account.deposit(amount);
261
+ }
262
+ },
263
+ retry: false,
264
+ onSuccess: (...args) => {
265
+ queryClient.invalidateQueries({ queryKey: contextKeys.account.all });
266
+ queryClient.invalidateQueries({ queryKey: contextKeys.portfolio.all });
267
+ options?.onSuccess?.(...args);
268
+ },
269
+ ...options
270
+ });
271
+ }
272
+ function useWithdraw(options) {
273
+ const client = useContextClient();
274
+ const queryClient = useQueryClient();
275
+ return useMutation({
276
+ mutationFn: (amount) => client.account.withdraw(amount),
277
+ retry: false,
278
+ onSuccess: (...args) => {
279
+ queryClient.invalidateQueries({ queryKey: contextKeys.account.all });
280
+ queryClient.invalidateQueries({ queryKey: contextKeys.portfolio.all });
281
+ options?.onSuccess?.(...args);
282
+ },
283
+ ...options
284
+ });
285
+ }
286
+
287
+ // src/hooks/useOrders.ts
288
+ import { useQuery as useQuery4 } from "@tanstack/react-query";
289
+ function useOrders(params, options) {
290
+ const client = useContextClient();
291
+ return useQuery4({
292
+ queryKey: contextKeys.orders.list(params),
293
+ queryFn: () => client.orders.list(params),
294
+ ...options
295
+ });
296
+ }
297
+ function useOrder(orderId, options) {
298
+ const client = useContextClient();
299
+ return useQuery4({
300
+ queryKey: contextKeys.orders.get(orderId),
301
+ queryFn: () => client.orders.get(orderId),
302
+ enabled: !!orderId,
303
+ ...options
304
+ });
305
+ }
306
+
307
+ // src/hooks/useOrderMutations.ts
308
+ import { useMutation as useMutation2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
309
+ function useCreateOrder(options) {
310
+ const client = useContextClient();
311
+ const queryClient = useQueryClient2();
312
+ return useMutation2({
313
+ mutationFn: (req) => client.orders.create(req),
314
+ retry: false,
315
+ onSuccess: (...args) => {
316
+ queryClient.invalidateQueries({ queryKey: contextKeys.orders.all });
317
+ queryClient.invalidateQueries({ queryKey: contextKeys.markets.orderbook(args[1].marketId) });
318
+ queryClient.invalidateQueries({ queryKey: contextKeys.portfolio.all });
319
+ options?.onSuccess?.(...args);
320
+ },
321
+ ...options
322
+ });
323
+ }
324
+ function useCreateMarketOrder(options) {
325
+ const client = useContextClient();
326
+ const queryClient = useQueryClient2();
327
+ return useMutation2({
328
+ mutationFn: (req) => client.orders.createMarket(req),
329
+ retry: false,
330
+ onSuccess: (...args) => {
331
+ queryClient.invalidateQueries({ queryKey: contextKeys.orders.all });
332
+ queryClient.invalidateQueries({ queryKey: contextKeys.markets.orderbook(args[1].marketId) });
333
+ queryClient.invalidateQueries({ queryKey: contextKeys.portfolio.all });
334
+ options?.onSuccess?.(...args);
335
+ },
336
+ ...options
337
+ });
338
+ }
339
+ function useCancelOrder(options) {
340
+ const client = useContextClient();
341
+ const queryClient = useQueryClient2();
342
+ return useMutation2({
343
+ mutationFn: (nonce) => client.orders.cancel(nonce),
344
+ retry: false,
345
+ onSuccess: (...args) => {
346
+ queryClient.invalidateQueries({ queryKey: contextKeys.orders.all });
347
+ options?.onSuccess?.(...args);
348
+ },
349
+ ...options
350
+ });
351
+ }
352
+ function useCancelReplace(options) {
353
+ const client = useContextClient();
354
+ const queryClient = useQueryClient2();
355
+ return useMutation2({
356
+ mutationFn: ({ cancelNonce, newOrder }) => client.orders.cancelReplace(cancelNonce, newOrder),
357
+ retry: false,
358
+ onSuccess: (...args) => {
359
+ queryClient.invalidateQueries({ queryKey: contextKeys.orders.all });
360
+ queryClient.invalidateQueries({ queryKey: contextKeys.portfolio.all });
361
+ options?.onSuccess?.(...args);
362
+ },
363
+ ...options
364
+ });
365
+ }
366
+
367
+ // src/hooks/useQuestions.ts
368
+ import { useMutation as useMutation3, useQueryClient as useQueryClient3 } from "@tanstack/react-query";
369
+ function useSubmitQuestion(options) {
370
+ const client = useContextClient();
371
+ return useMutation3({
372
+ mutationFn: (question) => client.questions.submit(question),
373
+ retry: false,
374
+ ...options
375
+ });
376
+ }
377
+ function useSubmitAndWait(options) {
378
+ const client = useContextClient();
379
+ const queryClient = useQueryClient3();
380
+ return useMutation3({
381
+ mutationFn: (input) => client.questions.submitAndWait(input.question, input.options),
382
+ retry: false,
383
+ onSuccess: (...args) => {
384
+ queryClient.invalidateQueries({ queryKey: contextKeys.markets.all });
385
+ options?.onSuccess?.(...args);
386
+ },
387
+ ...options
388
+ });
389
+ }
390
+ function useCreateMarket(options) {
391
+ const client = useContextClient();
392
+ const queryClient = useQueryClient3();
393
+ return useMutation3({
394
+ mutationFn: (questionId) => client.markets.create(questionId),
395
+ retry: false,
396
+ onSuccess: (...args) => {
397
+ queryClient.invalidateQueries({ queryKey: contextKeys.markets.all });
398
+ options?.onSuccess?.(...args);
399
+ },
400
+ ...options
401
+ });
402
+ }
403
+ function useAgentSubmit(options) {
404
+ const client = useContextClient();
405
+ return useMutation3({
406
+ mutationFn: (draft) => client.questions.agentSubmit(draft),
407
+ retry: false,
408
+ ...options
409
+ });
410
+ }
411
+ function useAgentSubmitAndWait(options) {
412
+ const client = useContextClient();
413
+ const queryClient = useQueryClient3();
414
+ return useMutation3({
415
+ mutationFn: (input) => client.questions.agentSubmitAndWait(input.draft, input.options),
416
+ retry: false,
417
+ onSuccess: (...args) => {
418
+ queryClient.invalidateQueries({ queryKey: contextKeys.markets.all });
419
+ options?.onSuccess?.(...args);
420
+ },
421
+ ...options
422
+ });
423
+ }
424
+ export {
425
+ ContextProvider,
426
+ ContextWalletError,
427
+ contextKeys,
428
+ useAccountSetup,
429
+ useAccountStatus,
430
+ useAgentSubmit,
431
+ useAgentSubmitAndWait,
432
+ useBalance,
433
+ useCancelOrder,
434
+ useCancelReplace,
435
+ useClaimable,
436
+ useContextClient,
437
+ useCreateMarket,
438
+ useCreateMarketOrder,
439
+ useCreateOrder,
440
+ useDeposit,
441
+ useLatestOracleQuote,
442
+ useMarket,
443
+ useMarketActivity,
444
+ useMarkets,
445
+ useOracle,
446
+ useOrder,
447
+ useOrderbook,
448
+ useOrders,
449
+ usePortfolio,
450
+ usePortfolioStats,
451
+ usePositions,
452
+ usePriceHistory,
453
+ useQuotes,
454
+ useSearchMarkets,
455
+ useSimulateTrade,
456
+ useSubmitAndWait,
457
+ useSubmitQuestion,
458
+ useWithdraw
459
+ };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "context-markets-react",
3
+ "version": "0.1.0",
4
+ "description": "React hooks for Context Markets — built on context-markets and TanStack Query",
5
+ "license": "MIT",
6
+ "author": "Context",
7
+ "homepage": "https://docs.context.markets/agents/react-sdk",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/contextwtf/context-react.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/contextwtf/context-react/issues"
14
+ },
15
+ "keywords": [
16
+ "prediction-markets",
17
+ "context",
18
+ "react",
19
+ "hooks",
20
+ "wagmi",
21
+ "web3",
22
+ "tanstack-query"
23
+ ],
24
+ "type": "module",
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": "./dist/index.js",
30
+ "types": "./dist/index.d.ts"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "peerDependencies": {
37
+ "context-markets": ">=0.4.0",
38
+ "@tanstack/react-query": ">=5.0.0",
39
+ "react": ">=18.0.0",
40
+ "viem": ">=2.0.0",
41
+ "wagmi": ">=2.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "context-markets": "^0.4.0",
45
+ "@tanstack/react-query": "^5.0.0",
46
+ "@testing-library/react": "^16.0.0",
47
+ "@types/react": "^19.2.14",
48
+ "@types/react-dom": "^19.2.3",
49
+ "jsdom": "^25.0.0",
50
+ "react": "^18.0.0",
51
+ "react-dom": "^18.0.0",
52
+ "tsup": "^8.0.0",
53
+ "typescript": "^5.5.0",
54
+ "viem": "^2.23.0",
55
+ "vitest": "^3.0.0",
56
+ "wagmi": "^2.0.0"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "vitest run"
62
+ }
63
+ }