@agg-build/hooks 1.0.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/README.md ADDED
@@ -0,0 +1,403 @@
1
+ # @agg-build/hooks
2
+
3
+ React hooks and providers for the [AGG](https://docs.agg.market/) prediction market aggregator.
4
+ Wraps [`@agg-build/sdk`](https://www.npmjs.com/package/@agg-build/sdk) with React context, shared auth/session
5
+ state, TanStack Query–powered data fetching, and live WebSocket streams.
6
+
7
+ ## What it is
8
+
9
+ `@agg-build/hooks` is the React bindings layer. It owns the `AggClient` inside a provider, keeps auth
10
+ and balance state in sync across your component tree, and exposes hooks for every AGG surface —
11
+ markets, orderbooks, charts, live trades, execution, managed wallets, deposits, search, and UI
12
+ config. Data hooks are backed by [TanStack Query](https://tanstack.com/query), and live-data hooks
13
+ are backed by the SDK's `AggWebSocket`.
14
+
15
+ ## When to use this package
16
+
17
+ - You are building a React app and want hooks instead of calling the SDK directly.
18
+ - You want a single provider that manages session, UI config, balances, and WebSocket lifecycle.
19
+ - You plan to render AGG trading UI with [`@agg-build/ui`](https://www.npmjs.com/package/@agg-build/ui) or the
20
+ modular auth UI in [`@agg-build/auth`](https://www.npmjs.com/package/@agg-build/auth) — both require this
21
+ package.
22
+
23
+ If you are not using React, use [`@agg-build/sdk`](https://www.npmjs.com/package/@agg-build/sdk) directly.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ npm install @agg-build/sdk @agg-build/hooks
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ ```tsx
34
+ import { AggProvider } from "@agg-build/hooks";
35
+ import { createAggClient } from "@agg-build/sdk";
36
+
37
+ const client = createAggClient({
38
+ baseUrl: "https://api.agg.market",
39
+ appId: "your-app-id",
40
+ wsUrl: "wss://ws.agg.market",
41
+ });
42
+
43
+ export function App() {
44
+ return (
45
+ <AggProvider
46
+ client={client}
47
+ config={{
48
+ general: { locale: "en-US", theme: "dark" },
49
+ features: { enableAnimations: true, enableLiveUpdates: true },
50
+ }}
51
+ >
52
+ <YourApp />
53
+ </AggProvider>
54
+ );
55
+ }
56
+ ```
57
+
58
+ `AggProvider` composes the SDK, UI config, balance, and WebSocket contexts into one. If you
59
+ prefer to compose them yourself, the individual providers (`AggSdkProvider`, `AggUiProvider`,
60
+ `AggBalanceProvider`) are exported too.
61
+
62
+ > `AggProvider` creates its own internal `QueryClientProvider` if one is not already in the tree,
63
+ > so you don't need to install or configure TanStack Query to get started. Drop in your own
64
+ > `<QueryClientProvider>` if you want to share a cache with the rest of your app.
65
+
66
+ ### Signing in with a wallet
67
+
68
+ `useAggAuth` is a lower-level hook for wiring your own wallet UI. Pass a `signMessage` callback
69
+ from wagmi (Ethereum) or a Solana wallet adapter:
70
+
71
+ ```tsx
72
+ import { useAggAuth } from "@agg-build/hooks";
73
+ import { useAccount, useSignMessage } from "wagmi";
74
+
75
+ function SignIn() {
76
+ const { address, chainId } = useAccount();
77
+ const { signMessageAsync } = useSignMessage();
78
+ const { signIn, signOut, isAuthenticated, user, isLoading, error } = useAggAuth({
79
+ signMessage: (message) => signMessageAsync({ message }),
80
+ address,
81
+ chainId,
82
+ });
83
+
84
+ if (isAuthenticated) {
85
+ return (
86
+ <div>
87
+ <p>Signed in as {user?.id}</p>
88
+ <button onClick={() => signOut()}>Sign out</button>
89
+ </div>
90
+ );
91
+ }
92
+
93
+ return (
94
+ <button disabled={isLoading} onClick={() => signIn("Sign in to AGG")}>
95
+ Sign in with Ethereum
96
+ </button>
97
+ );
98
+ }
99
+ ```
100
+
101
+ For Solana, pass a `signMessage` that signs the raw UTF-8 bytes and returns a base58-encoded
102
+ signature:
103
+
104
+ ```tsx
105
+ import bs58 from "bs58";
106
+ import { useWallet } from "@solana/wallet-adapter-react";
107
+ import { useAggAuth } from "@agg-build/hooks";
108
+
109
+ function SolanaSignIn() {
110
+ const { publicKey, signMessage } = useWallet();
111
+ const { signIn, isLoading } = useAggAuth({
112
+ address: publicKey?.toBase58(),
113
+ chain: "solana",
114
+ chainId: "mainnet",
115
+ signMessage: async (message) => {
116
+ const bytes = await signMessage!(new TextEncoder().encode(message));
117
+ return bs58.encode(bytes);
118
+ },
119
+ });
120
+
121
+ return (
122
+ <button disabled={isLoading} onClick={() => signIn("Sign in to AGG")}>
123
+ Sign in with Solana
124
+ </button>
125
+ );
126
+ }
127
+ ```
128
+
129
+ For a fully packaged connect/sign-in UI with SIWE, SIWS, Google, Apple, Twitter/X, and email
130
+ magic-link support, use [`@agg-build/auth`](https://www.npmjs.com/package/@agg-build/auth).
131
+
132
+ ### Rendering market data
133
+
134
+ ```tsx
135
+ import { useVenueEvents, useMarketOrderbook } from "@agg-build/hooks";
136
+
137
+ function MarketList() {
138
+ const { data, isLoading, fetchNextPage, hasNextPage } = useVenueEvents({
139
+ limit: 20,
140
+ });
141
+
142
+ if (isLoading) return <p>Loading…</p>;
143
+
144
+ return (
145
+ <>
146
+ {data?.pages
147
+ .flatMap((page) => page.data)
148
+ .map((event) => (
149
+ <article key={event.id}>{event.title}</article>
150
+ ))}
151
+ {hasNextPage ? <button onClick={() => fetchNextPage()}>Load more</button> : null}
152
+ </>
153
+ );
154
+ }
155
+
156
+ function LiveOrderbook({ venueMarketIds }: { venueMarketIds: string[] }) {
157
+ const { book, isLoading } = useMarketOrderbook({ venueMarketIds });
158
+ if (isLoading) return null;
159
+ return <pre>{JSON.stringify(book, null, 2)}</pre>;
160
+ }
161
+ ```
162
+
163
+ ### Linking an external partner user ID
164
+
165
+ Generate the signed assertion on your backend with `signExternalId()` from `@agg-build/sdk/server`, then
166
+ call `useExternalId()` on the frontend:
167
+
168
+ ```tsx
169
+ import { useEffect, useRef } from "react";
170
+ import { useExternalId } from "@agg-build/hooks";
171
+
172
+ function LinkPartnerAccount({
173
+ assertion,
174
+ }: {
175
+ assertion: { externalId: string; timestamp: number; hmac: string } | null;
176
+ }) {
177
+ const { linkExternalId } = useExternalId();
178
+ const lastLinked = useRef<string | null>(null);
179
+
180
+ useEffect(() => {
181
+ if (!assertion) return;
182
+ const key = `${assertion.externalId}:${assertion.timestamp}`;
183
+ if (lastLinked.current === key) return;
184
+ lastLinked.current = key;
185
+ void linkExternalId(assertion).catch(() => {
186
+ lastLinked.current = null;
187
+ });
188
+ }, [assertion, linkExternalId]);
189
+
190
+ return null;
191
+ }
192
+ ```
193
+
194
+ ## Main hooks
195
+
196
+ ### Core
197
+
198
+ | Hook | Description |
199
+ | --------------------- | ------------------------------------------------------------- |
200
+ | `useAggClient()` | Access the underlying `AggClient` instance |
201
+ | `useAggAuth(options)` | Wallet-signature helper for SIWE/SIWS sign-in |
202
+ | `useAggAuthContext()` | Full auth context (isAuthenticated, user, signIn, signOut, …) |
203
+ | `useAggAuthState()` | Read-only auth state |
204
+ | `useLinkAccount()` | Link an additional auth provider to the current account |
205
+ | `useExternalId()` | Link a backend-signed partner user ID |
206
+ | `useGeoBlock()` | Reactive geo-block state for restricted regions |
207
+
208
+ ### Market data
209
+
210
+ | Hook | Description |
211
+ | -------------------------------- | --------------------------------------------------- |
212
+ | `useVenueEvents(options?)` | Events with cursor-based infinite pagination |
213
+ | `useVenueEvent({ eventId })` | Fetch a single event by ID |
214
+ | `useEnrichedVenueEvent(options)` | Event + enriched venueMarkets with full market data |
215
+ | `useVenueMarkets(options?)` | Markets with filters (infinite pagination) |
216
+ | `useCategories(options?)` | Market categories (infinite pagination) |
217
+ | `useSearch(options?)` | Typeahead search across events |
218
+
219
+ ### Orderbooks & routing
220
+
221
+ | Hook | Description |
222
+ | ----------------------------- | --------------------------------------------------- |
223
+ | `useMarketOrderbook(options)` | Canonical orderbook with live WS updates |
224
+ | `useOrderBook(options)` | Batch multiple venue orderbooks into one result |
225
+ | `useOrderbookQuote(options)` | Compute a quote from the orderbook for a size/side |
226
+ | `useSmartRoute(options)` | Optimal order routing across venues via MILP solver |
227
+
228
+ ### Charts
229
+
230
+ | Hook | Description |
231
+ | ------------------------------- | --------------------------------------------------- |
232
+ | `useMarketChart(options)` | Historical candles with live WS updates |
233
+ | `useLiveCandles(options)` | Merge REST historical + live `CandleBuilder` output |
234
+ | `useLiveCandleOverlay(options)` | Scale candles for chart rendering with live overlay |
235
+
236
+ ### Live data
237
+
238
+ | Hook | Description |
239
+ | ------------------------------------ | ------------------------------------------------- |
240
+ | `useLiveMarket(canonicalMarketId)` | Subscribe to live orderbook + trades for a market |
241
+ | `useLiveTrades(canonicalMarketId)` | Recent trades only (max 50, newest first) |
242
+ | `useLiveOutcomePrices(venueMarkets)` | Derive live display prices for all outcomes |
243
+ | `useVenueMarketMidpoints(options)` | Midpoints for visible markets |
244
+ | `useViewportMidpoints(options)` | Midpoints batched for the visible viewport |
245
+ | `useVisibleIds(options)` | Track IDs currently visible in a scroll container |
246
+
247
+ ### WebSocket
248
+
249
+ | Hook | Description |
250
+ | ------------------------------------------------------- | ------------------------------------------------ |
251
+ | `useAggWebSocket()` | Access the raw `AggWebSocket` instance |
252
+ | `useOnOrderSubmitted(callback)` | Subscribe to order submission events |
253
+ | `useOnBalanceUpdate(callback)` | Subscribe to balance update events |
254
+ | `useOnRedeemEvent(callback)` | Subscribe to redeem events |
255
+ | `useEventOrderbookData(venueMarkets, selectedMarketId)` | WS orderbook subscription for an event's markets |
256
+
257
+ ### Balances
258
+
259
+ | Hook | Description |
260
+ | ------------------------ | ------------------------------------------------- |
261
+ | `useAggBalance()` | Balance context (totalBalance, breakdown, venues) |
262
+ | `useAggBalanceContext()` | Full balance context with refetch |
263
+ | `useAggBalanceState()` | Read-only balance state |
264
+ | `useManagedBalances()` | Query unified managed wallet balances |
265
+
266
+ ### Orders & positions
267
+
268
+ | Hook | Description |
269
+ | --------------------------------- | ------------------------------------------------- |
270
+ | `useOrders(options?)` | List trade-executor orders (offset pagination) |
271
+ | `useExecutionOrders(options?)` | List execution orders (cursor pagination) |
272
+ | `useExecutionPositions(options?)` | List execution positions (cursor pagination) |
273
+ | `useUserHoldings(options)` | Fetch venue-specific holdings |
274
+ | `usePositions(options?)` | Query user positions grouped by matched market |
275
+ | `useUserActivity(options?)` | Unified activity feed (trades, deposits, bridges) |
276
+
277
+ ### Managed execution
278
+
279
+ | Hook | Description |
280
+ | ------------------------------- | -------------------------------------------------------------- |
281
+ | `useQuoteManaged(options?)` | Request a managed execution quote (2-min TTL) |
282
+ | `useExecuteManaged(options?)` | Execute a previously quoted managed trade |
283
+ | `useValidateManaged(options?)` | Pre-validate balances/bridge without quoting |
284
+ | `useWithdrawManaged(options?)` | Withdraw from managed wallets |
285
+ | `useSyncBalances(options?)` | Trigger on-chain balance sync |
286
+ | `useExecutionProgress(options)` | Track execution through phases (pending → submitted → updated) |
287
+ | `useRedeem()` | Claim winnings from resolved markets |
288
+ | `useRedeemEligibleCount()` | Count of positions eligible to redeem |
289
+
290
+ ### Deposits (subpath)
291
+
292
+ Import from `@agg-build/hooks/deposit` to keep wallet-heavy hooks out of your main bundle:
293
+
294
+ | Hook | Description |
295
+ | ------------------------------- | ------------------------------------------------------- |
296
+ | `useDepositFlow(options?)` | End-to-end deposit flow (select token → send → confirm) |
297
+ | `useWalletTokenBalance(params)` | Read ERC-20 / SPL balance for the connected wallet |
298
+ | `useWalletSendToken(params)` | Execute a transfer using the connected wallet |
299
+ | `useWalletTransactionStatus()` | Poll on-chain status for a transfer |
300
+ | `useDepositAddresses(options?)` | Managed wallet deposit addresses |
301
+ | `useSyncBalances(options?)` | Re-expose from the main entry for colocated imports |
302
+ | `normalizeWalletError(error)` | Convert wallet-library errors to a friendly shape |
303
+
304
+ ### Ramps
305
+
306
+ | Hook | Description |
307
+ | ------------------ | ---------------------------- |
308
+ | `useRampQuotes()` | Query on/off-ramp quotes |
309
+ | `useRampSession()` | Create a ramp widget session |
310
+
311
+ ### UI config & utilities
312
+
313
+ | Hook | Description |
314
+ | -------------------------------- | ---------------------------------------- |
315
+ | `useSdkUiConfig()` | Read the SDK-level UI config |
316
+ | `useAggUiConfig()` | Read the full AGG UI config |
317
+ | `useAggLabels()` / `useLabels()` | Access UI label strings |
318
+ | `useEventTradingContext()` | Event/market/outcome selection |
319
+ | `useDebouncedValue(value, ms)` | Debounce a value by delay |
320
+ | `useAppConfig()` | Partner app config (feature flags, etc.) |
321
+
322
+ ## Providers
323
+
324
+ | Provider | Purpose |
325
+ | ------------------------ | -------------------------------------------------------- |
326
+ | `AggProvider` | One-stop provider: SDK + UI config + balance + WebSocket |
327
+ | `AggSdkProvider` | SDK + auth state only |
328
+ | `AggUiProvider` | UI config (labels, theme, feature flags, search state) |
329
+ | `AggBalanceProvider` | Balance context (totals, breakdown) |
330
+ | `EventListStateProvider` | Shared pagination/filter state for event lists |
331
+
332
+ ### UI config
333
+
334
+ `AggProvider` accepts a sectioned config object:
335
+
336
+ - `enableLogs` / `enableWebsocketsLogs` — turn on debug logging
337
+ - `general` — `locale`, `theme` (`"light" | "dark"`), `rootClassName`, `labels`
338
+ - `features` — `showVenueLogo`, `enableAnimations`, `enableLiveUpdates`, `enableGradients`
339
+ - `market` — `arbitrageThreshold`
340
+ - `chart` — `defaultChartTimeRange`, `selectedChartTimeRange`
341
+ - `search` — provider-owned search state + callbacks for host-app routing/analytics
342
+
343
+ `locale`, `theme`, and `selectedChartTimeRange` are automatically persisted to `localStorage`.
344
+
345
+ ## Query keys
346
+
347
+ For direct React Query cache access (e.g. `queryClient.invalidateQueries()`):
348
+
349
+ ```typescript
350
+ import { executionKeys } from "@agg-build/hooks";
351
+
352
+ queryClient.invalidateQueries({ queryKey: executionKeys.balances() });
353
+ queryClient.invalidateQueries({ queryKey: executionKeys.positions() });
354
+ queryClient.invalidateQueries({ queryKey: executionKeys.orders() });
355
+ ```
356
+
357
+ `executionKeys` is the only key builder exported publicly — market data queries are managed
358
+ internally by the WebSocket provider.
359
+
360
+ ## Behavior notes
361
+
362
+ - `useOrderbookQuote` debounces `size` changes by 300 ms before querying.
363
+ - `useDepositAddresses` polls every 3 s while the managed wallet is being provisioned
364
+ (`ready === false`), then switches to 60 s stale time.
365
+ - `useLiveCandles` merges REST historical candles with live `CandleBuilder` output; on collision
366
+ the live version wins.
367
+ - For binary markets, the first outcome gets the midpoint and the second gets `1 − midpoint`.
368
+ - `CandleBuilder` batches `onChange` callbacks at ~16 ms (rAF in browsers, setTimeout otherwise).
369
+ - Execution mutations (`useExecuteManaged`, `useWithdrawManaged`, `useSyncBalances`)
370
+ auto-invalidate related balance/position/order queries on success.
371
+
372
+ ## Entrypoints
373
+
374
+ | Entry | Purpose |
375
+ | -------------------------- | --------------------------------------------------- |
376
+ | `@agg-build/hooks` | All providers and hooks |
377
+ | `@agg-build/hooks/deposit` | Wallet-heavy deposit hooks (tree-shakeable subpath) |
378
+
379
+ ## Peer dependencies
380
+
381
+ Required:
382
+
383
+ - `@agg-build/sdk`
384
+ - `react` ^18.0.0 or ^19.0.0
385
+
386
+ Optional (only needed for wallet-based sign-in / deposits):
387
+
388
+ - `wagmi` ^2.0.0 (SIWE + ERC-20 deposits)
389
+ - `viem` ^2.0.0 (paired with `wagmi`)
390
+ - `@solana/wallet-adapter-react` ^0.15.0 (SIWS + SPL deposits)
391
+ - `@solana/web3.js` ^1.95.0
392
+
393
+ ## Links
394
+
395
+ - Documentation — <https://docs.agg.market/>
396
+ - Demo app — <https://demo.agg.market/>
397
+ - Vanilla SDK — [`@agg-build/sdk`](https://www.npmjs.com/package/@agg-build/sdk)
398
+ - Trading UI — [`@agg-build/ui`](https://www.npmjs.com/package/@agg-build/ui)
399
+ - Connect / sign-in UX — [`@agg-build/auth`](https://www.npmjs.com/package/@agg-build/auth)
400
+
401
+ ## License
402
+
403
+ MIT