@agg-build/hooks

中文文档
4.37.0发布于 2026/11/06MITTypeScriptESM + CJS近 30 天下载 4233

React hooks and providers for the AGG prediction market aggregator. Wraps @agg-build/sdk with TanStack Query, shared session state, and live WebSocket data.

原始使用文档
文档目录28 节
  1. What it is
  2. When to use this package
  3. Install
  4. Quick start
  5. Signing in with a wallet
  6. Rendering market data
  7. Linking an external partner user ID
  8. Main hooks
  9. Core
  10. Market data
  11. Orderbooks & routing
  12. Charts
  13. Live data
  14. WebSocket
  15. Balances
  16. Orders & positions
  17. Managed execution
  18. Deposits (subpath)
  19. Ramps
  20. UI config & utilities
  21. Providers
  22. UI config
  23. Query keys
  24. Behavior notes
  25. Entrypoints
  26. Peer dependencies
  27. Links
  28. License

@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/ui or 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/hooks

Quick start

import { AggProvider, QueryClient, QueryClientProvider } 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",
  // Optional: orderbookUrl: "wss://ob.agg.market", orderbookLatency: "realtime",
  // With orderbookUrl set, orderbook isLive follows that socket. Trades stay on wsUrl.
});
const queryClient = new QueryClient();

export function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AggProvider
        client={client}
        config={{
          general: { locale: "en-US", theme: "dark" },
          features: { enableAnimations: true, enableLiveUpdates: true },
        }}
      >
        <YourApp />
      </AggProvider>
    </QueryClientProvider>
  );
}

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.

AggProvider uses TanStack Query for shared request and live-data caches, so a QueryClientProvider ancestor is required. The package re-exports QueryClient and QueryClientProvider for hooks-only consumers.

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

HookDescription
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

HookDescription
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

HookDescription
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

HookDescription
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

HookDescription
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

HookDescription
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

HookDescription
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

HookDescription
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)
useLeaderboard(options?)Trader leaderboard by P&L or volume (cursor pagination)

Managed execution

HookDescription
useExecuteManaged(options?)Fill a quote from useSmartRoute — see note below
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

To quote and fill, take the quote from useSmartRoute and pass its quoteId to useExecuteManaged.

const buyRoute = useSmartRoute({
  venueMarketOutcomeId,
  tradeSide: "buy",
  maxSpend: 50,
});

const sellRoute = useSmartRoute({
  venueMarketOutcomeId,
  tradeSide: "sell",
  sellShares: 10,
});

Removed in v4. useQuoteManaged was deleted — it wrapped client.quoteManaged(), whose endpoint (POST /execution/quote) does not exist on the API, so the call only ever returned 404.

Deposits (subpath)

Import from @agg-build/hooks/deposit to keep wallet-heavy hooks out of your main bundle:

HookDescription
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

HookDescription
useRampQuotes()Query on/off-ramp quotes
useRampSession()Create a ramp widget session

UI config & utilities

HookDescription
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

ProviderPurpose
AggProviderOne-stop provider: SDK + UI config + balance + WebSocket
AggSdkProviderSDK + auth state only
AggUiProviderUI config (labels, theme, feature flags, search state)
AggBalanceProviderBalance context (totals, breakdown)
EventListStateProviderShared pagination/filter state for event lists

UI config

AggProvider accepts a sectioned config object:

  • enableLogs / enableWebsocketsLogs — turn on debug logging
  • general — locale, theme ("light" | "dark"), rootClassName, labels
  • features — UI behavior flags including enableAnimations, enableLiveUpdates, enableVenueEventDiscoveryFilters, and enableEventDiscoveryUrlPersistence
  • market — arbitrageThreshold, maxMidpointIdsPerRequest for proxy/CDN-safe midpoint batching
  • chart — defaultChartTimeRange, selectedChartTimeRange
  • search — 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

  • useOrderbookQuote debounces size changes by 300 ms before querying.
  • useDepositAddresses polls every 3 s while the managed wallet is being provisioned (ready === false), then switches to 60 s stale time.
  • useLiveCandles merges REST historical candles with live CandleBuilder output; on collision the live version wins.
  • For binary markets, the first outcome gets the midpoint and the second gets 1 − midpoint.
  • CandleBuilder batches onChange callbacks at ~16 ms (rAF in browsers, setTimeout otherwise).
  • Execution mutations (useExecuteManaged, useWithdrawManaged, useSyncBalances) auto-invalidate related balance/position/order queries on success.

Entrypoints

EntryPurpose
@agg-build/hooksAll providers and hooks
@agg-build/hooks/depositWallet-heavy deposit hooks (tree-shakeable subpath)

Peer dependencies

Required:

  • @agg-build/sdk
  • react ^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 with wagmi)
  • @solana/wallet-adapter-react ^0.15.0 (SIWS + SPL deposits)
  • @solana/web3.js ^1.95.0

License

MIT

版本与发布记录

@agg-build/hooks 共发布 60 个版本,首次发布于 2026/04/28;过去 12 个月发布了 60 个版本。

版本发布日期距今
4.37.0latest2026/11/06今天
4.36.12026/11/041 天前
4.36.02026/11/042 天前
4.34.02026/10/306 天前
4.33.02026/10/307 天前
4.32.02026/10/289 天前

关于 @agg-build/hooks 的常见问题

@agg-build/hooks 是什么?

React hooks and providers for the AGG prediction market aggregator. Wraps @agg-build/sdk with TanStack Query, shared session state, and live WebSocket data.

如何安装 @agg-build/hooks?

在项目目录运行 npm install @agg-build/hooks,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.0.0 || ^19.0.0)、@agg-build/sdk(^4.37.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@agg-build/hooks 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agg-build/hooks 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@agg-build/hooks 可以商用吗?

@agg-build/hooks 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@agg-build/hooks 的下载量有多少?

根据 npm 官方下载统计,@agg-build/hooks 在 2026/10/05 – 2026/11/03 这 30 天内被下载 4,233 次,日均约 141 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agg-build/hooks 还在维护吗?

最新版本 4.37.0 发布于 2026/11/06(今天);至今共发布 60 个版本,其中过去 12 个月发布了 60 个;首次发布于 2026/04/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。