@agg-build/hooks
v1.2.0
Published
React hooks and providers for the AGG prediction market aggregator. Wraps @agg-build/sdk with TanStack Query, shared session state, and live WebSocket data.
Readme
@agg-build/hooks
React hooks and providers for the AGG prediction market aggregator.
Wraps @agg-build/sdk with React context, shared auth/session
state, TanStack Query–powered data fetching, and live WebSocket streams.
What it is
@agg-build/hooks is the React bindings layer. It owns the AggClient inside a provider, keeps auth
and balance state in sync across your component tree, and exposes hooks for every AGG surface —
markets, orderbooks, charts, live trades, execution, managed wallets, deposits, search, and UI
config. Data hooks are backed by TanStack Query, and live-data hooks
are backed by the SDK's AggWebSocket.
When to use this package
- You are building a React app and want hooks instead of calling the SDK directly.
- You want a single provider that manages session, UI config, balances, and WebSocket lifecycle.
- You plan to render AGG trading UI with
@agg-build/uior the modular auth UI in@agg-build/auth— both require this package.
If you are not using React, use @agg-build/sdk directly.
Install
npm install @agg-build/sdk @agg-build/hooksQuick start
import { AggProvider } from "@agg-build/hooks";
import { createAggClient } from "@agg-build/sdk";
const client = createAggClient({
baseUrl: "https://api.agg.market",
appId: "your-app-id",
wsUrl: "wss://ws.agg.market",
});
export function App() {
return (
<AggProvider
client={client}
config={{
general: { locale: "en-US", theme: "dark" },
features: { enableAnimations: true, enableLiveUpdates: true },
}}
>
<YourApp />
</AggProvider>
);
}AggProvider composes the SDK, UI config, balance, and WebSocket contexts into one. If you
prefer to compose them yourself, the individual providers (AggSdkProvider, AggUiProvider,
AggBalanceProvider) are exported too.
AggProvidercreates its own internalQueryClientProviderif one is not already in the tree, so you don't need to install or configure TanStack Query to get started. Drop in your own<QueryClientProvider>if you want to share a cache with the rest of your app.
Signing in with a wallet
useAggAuth is a lower-level hook for wiring your own wallet UI. Pass a signMessage callback
from wagmi (Ethereum) or a Solana wallet adapter:
import { useAggAuth } from "@agg-build/hooks";
import { useAccount, useSignMessage } from "wagmi";
function SignIn() {
const { address, chainId } = useAccount();
const { signMessageAsync } = useSignMessage();
const { signIn, signOut, isAuthenticated, user, isLoading, error } = useAggAuth({
signMessage: (message) => signMessageAsync({ message }),
address,
chainId,
});
if (isAuthenticated) {
return (
<div>
<p>Signed in as {user?.id}</p>
<button onClick={() => signOut()}>Sign out</button>
</div>
);
}
return (
<button disabled={isLoading} onClick={() => signIn("Sign in to AGG")}>
Sign in with Ethereum
</button>
);
}For Solana, pass a signMessage that signs the raw UTF-8 bytes and returns a base58-encoded
signature:
import bs58 from "bs58";
import { useWallet } from "@solana/wallet-adapter-react";
import { useAggAuth } from "@agg-build/hooks";
function SolanaSignIn() {
const { publicKey, signMessage } = useWallet();
const { signIn, isLoading } = useAggAuth({
address: publicKey?.toBase58(),
chain: "solana",
chainId: "mainnet",
signMessage: async (message) => {
const bytes = await signMessage!(new TextEncoder().encode(message));
return bs58.encode(bytes);
},
});
return (
<button disabled={isLoading} onClick={() => signIn("Sign in to AGG")}>
Sign in with Solana
</button>
);
}For a fully packaged connect/sign-in UI with SIWE, SIWS, Google, Apple, Twitter/X, and email
magic-link support, use @agg-build/auth.
Rendering market data
import { useVenueEvents, useMarketOrderbook } from "@agg-build/hooks";
function MarketList() {
const { data, isLoading, fetchNextPage, hasNextPage } = useVenueEvents({
limit: 20,
});
if (isLoading) return <p>Loading…</p>;
return (
<>
{data?.pages
.flatMap((page) => page.data)
.map((event) => (
<article key={event.id}>{event.title}</article>
))}
{hasNextPage ? <button onClick={() => fetchNextPage()}>Load more</button> : null}
</>
);
}
function LiveOrderbook({ venueMarketIds }: { venueMarketIds: string[] }) {
const { book, isLoading } = useMarketOrderbook({ venueMarketIds });
if (isLoading) return null;
return <pre>{JSON.stringify(book, null, 2)}</pre>;
}Linking an external partner user ID
Generate the signed assertion on your backend with signExternalId() from @agg-build/sdk/server, then
call useExternalId() on the frontend:
import { useEffect, useRef } from "react";
import { useExternalId } from "@agg-build/hooks";
function LinkPartnerAccount({
assertion,
}: {
assertion: { externalId: string; timestamp: number; hmac: string } | null;
}) {
const { linkExternalId } = useExternalId();
const lastLinked = useRef<string | null>(null);
useEffect(() => {
if (!assertion) return;
const key = `${assertion.externalId}:${assertion.timestamp}`;
if (lastLinked.current === key) return;
lastLinked.current = key;
void linkExternalId(assertion).catch(() => {
lastLinked.current = null;
});
}, [assertion, linkExternalId]);
return null;
}Main hooks
Core
| Hook | Description |
| --------------------- | ------------------------------------------------------------- |
| useAggClient() | Access the underlying AggClient instance |
| useAggAuth(options) | Wallet-signature helper for SIWE/SIWS sign-in |
| useAggAuthContext() | Full auth context (isAuthenticated, user, signIn, signOut, …) |
| useAggAuthState() | Read-only auth state |
| useLinkAccount() | Link an additional auth provider to the current account |
| useExternalId() | Link a backend-signed partner user ID |
| useGeoBlock() | Reactive geo-block state for restricted regions |
Market data
| Hook | Description |
| -------------------------------- | --------------------------------------------------- |
| useVenueEvents(options?) | Events with cursor-based infinite pagination |
| useVenueEvent({ eventId }) | Fetch a single event by ID |
| useEnrichedVenueEvent(options) | Event + enriched venueMarkets with full market data |
| useVenueMarkets(options?) | Markets with filters (infinite pagination) |
| useCategories(options?) | Market categories (infinite pagination) |
| useSearch(options?) | Typeahead search across events |
Orderbooks & routing
| Hook | Description |
| ----------------------------- | --------------------------------------------------- |
| useMarketOrderbook(options) | Canonical orderbook with live WS updates |
| useOrderBook(options) | Batch multiple venue orderbooks into one result |
| useOrderbookQuote(options) | Compute a quote from the orderbook for a size/side |
| useSmartRoute(options) | Optimal order routing across venues via MILP solver |
Charts
| Hook | Description |
| ------------------------------- | --------------------------------------------------- |
| useMarketChart(options) | Historical candles with live WS updates |
| useLiveCandles(options) | Merge REST historical + live CandleBuilder output |
| useLiveCandleOverlay(options) | Scale candles for chart rendering with live overlay |
Live data
| Hook | Description |
| ------------------------------------ | ------------------------------------------------- |
| useLiveMarket(canonicalMarketId) | Subscribe to live orderbook + trades for a market |
| useLiveTrades(canonicalMarketId) | Recent trades only (max 50, newest first) |
| useLiveOutcomePrices(venueMarkets) | Derive live display prices for all outcomes |
| useVenueMarketMidpoints(options) | Midpoints for visible markets |
| useViewportMidpoints(options) | Midpoints batched for the visible viewport |
| useVisibleIds(options) | Track IDs currently visible in a scroll container |
WebSocket
| Hook | Description |
| ------------------------------------------------------- | ------------------------------------------------ |
| useAggWebSocket() | Access the raw AggWebSocket instance |
| useOnOrderSubmitted(callback) | Subscribe to order submission events |
| useOnBalanceUpdate(callback) | Subscribe to balance update events |
| useOnRedeemEvent(callback) | Subscribe to redeem events |
| useEventOrderbookData(venueMarkets, selectedMarketId) | WS orderbook subscription for an event's markets |
Balances
| Hook | Description |
| ------------------------ | ------------------------------------------------- |
| useAggBalance() | Balance context (totalBalance, breakdown, venues) |
| useAggBalanceContext() | Full balance context with refetch |
| useAggBalanceState() | Read-only balance state |
| useManagedBalances() | Query unified managed wallet balances |
Orders & positions
| Hook | Description |
| --------------------------------- | ------------------------------------------------- |
| useOrders(options?) | List trade-executor orders (offset pagination) |
| useExecutionOrders(options?) | List execution orders (cursor pagination) |
| useExecutionPositions(options?) | List execution positions (cursor pagination) |
| useUserHoldings(options) | Fetch venue-specific holdings |
| usePositions(options?) | Query user positions grouped by matched market |
| useUserActivity(options?) | Unified activity feed (trades, deposits, bridges) |
Managed execution
| Hook | Description |
| ------------------------------- | -------------------------------------------------------------- |
| useQuoteManaged(options?) | Request a managed execution quote (2-min TTL) |
| useExecuteManaged(options?) | Execute a previously quoted managed trade |
| useValidateManaged(options?) | Pre-validate balances/bridge without quoting |
| useWithdrawManaged(options?) | Withdraw from managed wallets |
| useSyncBalances(options?) | Trigger on-chain balance sync |
| useExecutionProgress(options) | Track execution through phases (pending → submitted → updated) |
| useRedeem() | Claim winnings from resolved markets |
| useRedeemEligibleCount() | Count of positions eligible to redeem |
Deposits (subpath)
Import from @agg-build/hooks/deposit to keep wallet-heavy hooks out of your main bundle:
| Hook | Description |
| ------------------------------- | ------------------------------------------------------- |
| useDepositFlow(options?) | End-to-end deposit flow (select token → send → confirm) |
| useWalletTokenBalance(params) | Read ERC-20 / SPL balance for the connected wallet |
| useWalletSendToken(params) | Execute a transfer using the connected wallet |
| useWalletTransactionStatus() | Poll on-chain status for a transfer |
| useDepositAddresses(options?) | Managed wallet deposit addresses |
| useSyncBalances(options?) | Re-expose from the main entry for colocated imports |
| normalizeWalletError(error) | Convert wallet-library errors to a friendly shape |
Ramps
| Hook | Description |
| ------------------ | ---------------------------- |
| useRampQuotes() | Query on/off-ramp quotes |
| useRampSession() | Create a ramp widget session |
UI config & utilities
| Hook | Description |
| -------------------------------- | ---------------------------------------- |
| useSdkUiConfig() | Read the SDK-level UI config |
| useAggUiConfig() | Read the full AGG UI config |
| useAggLabels() / useLabels() | Access UI label strings |
| useEventTradingContext() | Event/market/outcome selection |
| useDebouncedValue(value, ms) | Debounce a value by delay |
| useAppConfig() | Partner app config (feature flags, etc.) |
Providers
| Provider | Purpose |
| ------------------------ | -------------------------------------------------------- |
| AggProvider | One-stop provider: SDK + UI config + balance + WebSocket |
| AggSdkProvider | SDK + auth state only |
| AggUiProvider | UI config (labels, theme, feature flags, search state) |
| AggBalanceProvider | Balance context (totals, breakdown) |
| EventListStateProvider | Shared pagination/filter state for event lists |
UI config
AggProvider accepts a sectioned config object:
enableLogs/enableWebsocketsLogs— turn on debug logginggeneral—locale,theme("light" | "dark"),rootClassName,labelsfeatures—showVenueLogo,enableAnimations,enableLiveUpdates,showFeesBreakdown,enableGradientsmarket—arbitrageThresholdchart—defaultChartTimeRange,selectedChartTimeRangesearch— provider-owned search state + callbacks for host-app routing/analytics
locale, theme, and selectedChartTimeRange are automatically persisted to localStorage.
Query keys
For direct React Query cache access (e.g. queryClient.invalidateQueries()):
import { executionKeys } from "@agg-build/hooks";
queryClient.invalidateQueries({ queryKey: executionKeys.balances() });
queryClient.invalidateQueries({ queryKey: executionKeys.positions() });
queryClient.invalidateQueries({ queryKey: executionKeys.orders() });executionKeys is the only key builder exported publicly — market data queries are managed
internally by the WebSocket provider.
Behavior notes
useOrderbookQuotedebouncessizechanges by 300 ms before querying.useDepositAddressespolls every 3 s while the managed wallet is being provisioned (ready === false), then switches to 60 s stale time.useLiveCandlesmerges REST historical candles with liveCandleBuilderoutput; on collision the live version wins.- For binary markets, the first outcome gets the midpoint and the second gets
1 − midpoint. CandleBuilderbatchesonChangecallbacks at ~16 ms (rAF in browsers, setTimeout otherwise).- Execution mutations (
useExecuteManaged,useWithdrawManaged,useSyncBalances) auto-invalidate related balance/position/order queries on success.
Entrypoints
| Entry | Purpose |
| -------------------------- | --------------------------------------------------- |
| @agg-build/hooks | All providers and hooks |
| @agg-build/hooks/deposit | Wallet-heavy deposit hooks (tree-shakeable subpath) |
Peer dependencies
Required:
@agg-build/sdkreact^18.0.0 or ^19.0.0
Optional (only needed for wallet-based sign-in / deposits):
wagmi^2.0.0 (SIWE + ERC-20 deposits)viem^2.0.0 (paired withwagmi)@solana/wallet-adapter-react^0.15.0 (SIWS + SPL deposits)@solana/web3.js^1.95.0
Links
- Documentation — https://docs.agg.market/
- Demo app — https://agg.market/
- Vanilla SDK —
@agg-build/sdk - Trading UI —
@agg-build/ui - Connect / sign-in UX —
@agg-build/auth
License
MIT
