> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portalhq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Trade prediction markets with Agg

> Link a Portal wallet to Agg, fund its balance, and trade, redeem and withdraw across prediction-market venues with the Web SDK.

Portal's Web SDK lets your users trade prediction markets on venues such as Polymarket, Kalshi and Limitless through the `portal.predictionMarkets.agg` API. This guide covers linking the user's wallet to Agg, discovering markets, funding the Agg balance, trading, redeeming and withdrawing.

> [!NOTE]
>
> `portal.predictionMarkets` requires `@portal-hq/web` 5.0.0 or later.

## Overview

With `portal.predictionMarkets.agg` you can:

* **Link** the user's Portal wallet to their Agg account with one signature
* **Discover** events, markets and outcomes, with live prices, order books and charts
* **Fund** the user's Agg balance from their Portal wallet
* **Buy and sell** outcomes at the best price across venues, or place **limit orders**
* **Redeem** winning positions and **withdraw** to the user's wallet

The [Agg integration page](https://docs.portalhq.io/integrations/Trading/agg.md#how-it-works) explains how Agg works: the managed balance, quotes and fills, and how venues settle.

The API has two kinds of methods:

* **Helpers** (`connect`, `isConnected`, `deposit`, `buy`, `sell`, `placeLimitOrder`, `redeemAll` and `withdraw`) run a whole flow and resolve with its result.
* **Route methods**, one per Portal API route except self-custody signature submission (`POST /orders/{quoteId}/signatures`), resolve with the response, wrapped as `{ data }`. See [Low-level APIs](#low-level-apis).

Chain ids are [CAIP-2](https://docs.portalhq.io/resources/chain-id-formatting.md), for example `eip155:137` for Polygon. Amounts you pass to the helpers are decimal strings, such as `'10'` or `'1.5'`.

## Prerequisites

Before using Agg, make sure you have:

* A properly initialized Portal client with the iframe ready (`portal.onReady`; see [The onReady hook](https://docs.portalhq.io/sdks/web/guide/create-a-wallet.md#the-onready-hook))
* An active wallet with an EVM address (see [Create a wallet](https://docs.portalhq.io/sdks/web/guide/create-a-wallet.md))
* Gas on the wallet for the chain you deposit from
* Agg set up for your environment: an Agg app, trusted proxy, and the integration enabled in your Portal Dashboard. Follow [Setup](https://docs.portalhq.io/integrations/Trading/agg.md#setup) on the Agg integration page.
* An `rpcConfig` entry for every chain the SDK signs or sends on: Polygon (`eip155:137`), where `connect` signs by default, and every chain you deposit from. The default `rpcConfig` covers the [13 built-in chains](https://docs.portalhq.io/sdks/web/guide/getting-started.md#initializing-portal). An explicit `rpcConfig` replaces the defaults rather than extending them. Without an entry, the helper fails with `MissingRpcUrl` and nothing is signed or sent.

> [!WARNING]
>
> **Linking and trading require a Portal client *without* [account abstraction](https://docs.portalhq.io/resources/account-abstraction.md).** Agg signs users in with the wallet's own key, so the Portal API refuses everything except discovery and market data for an account-abstracted client with `AGG_ACCOUNT_ABSTRACTION_UNSUPPORTED`. `isConnected()`, `getLink()` and `deleteLink()` reject with it too instead of reporting the client as unlinked. Discovery and market data still work.

> [!WARNING]
>
> **Live trading is geo-restricted.** Every venue blocks some countries, and the United States is blocked on all of them. Geofencing is your responsibility: read [Geo restrictions](https://docs.portalhq.io/integrations/Trading/agg.md#geo-restrictions) and [Compliance](https://docs.portalhq.io/integrations/Trading/agg.md#compliance) before you ship. Pass `mode: 'paper'` to simulate trades from any country while you build; confirm with Snag that paper trading is enabled for your Agg app first.

The examples in this guide use an `agg` instance:

```typescript theme={null}
import Portal from '@portal-hq/web'

const portal = new Portal({
  apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
  // Without rpcConfig, Portal's gateway serves the 13 built-in chains, Polygon included.
})

const agg = portal.predictionMarkets.agg
```

## Discovering markets

Discovery works before the user links. An event, such as an election, groups markets, and each market has outcomes. You trade an **outcome**, identified by `venueMarketOutcomes[].id` on its market.

```typescript theme={null}
const { data: page } = await agg.listEvents({ limit: 10 })

for (const event of page.data) {
  console.log(event.id, event.title)
}

// One event page: the event, its first markets and the outcomes to chart.
const { data: eventPage } = await agg.getEventBootstrap(page.data[0].id)
const market = eventPage.markets.data[0]

for (const outcome of market.venueMarketOutcomes) {
  console.log(outcome.id, outcome.label)
}

// The outcome the examples below trade.
const outcomeId = market.venueMarketOutcomes[0].id
```

Lists are paginated: pass `nextCursor` back as `cursor` while `hasMore` is `true`. Read an event's markets from `markets` on `getEventBootstrap`, not from `event.venueMarkets`, which can be empty there. Continue with `listMarkets({ venueEventId, cursor: markets.nextCursor })`.

The other discovery methods are `getEvent`, `listMarkets`, `search` (`{ q, type: 'events' | 'markets' }`), `listCategories`, `getVenueGeoPolicy` and `getAppConfig`.

## Linking the wallet

`connect` links the Portal wallet to the user's Agg account. It asks the Portal API for a sign-in message, signs it with `personal_sign` on the chain you pass (Polygon, `eip155:137`, by default), and completes the link.

```typescript theme={null}
const link = await agg.connect()

console.log(link.aggUserId, link.linkedAddress)
```

Nothing is signed unless the chain has an RPC URL configured and the sign-in message names the wallet's own address (`AddressMismatch` otherwise). If you use [signature approvals](https://docs.portalhq.io/sdks/web/guide/add-custom-signature-hooks.md), the signature reaches your approval hook as a normal `personal_sign`.

`isConnected()` reports whether the client is linked, and `deleteLink()` unlinks it.

A linked user's Agg session can still expire. Any call can then fail with the `AGG_LINK_REQUIRED` error id, even after `isConnected()` returned `true`. Run `connect` again and retry, or pass `autoReconnect: true` to a helper so it does that for you (see [Progress, cancellation and reconnecting](#progress-cancellation-and-reconnecting)).

## Market data and charts

* `getMidpoints(venueMarketIds)` and `getOrderbooks(venueMarketIds)` return live prices and books for a batch of markets. Each order book entry's `requestedMarket` carries the `sizeStepRaw` and `minSizeRaw` a limit order must respect.
* `getOutcomeOrderbook(outcomeId)` returns one outcome's ladder and depth.
* `getChartBars` returns OHLCV bars for one outcome. `getChartHistoryManifest` returns finalized history for long ranges as CDN chunks.

```typescript theme={null}
const { data: bars } = await agg.getChartBars({
  venueMarketOutcomeId: outcomeId,
  to: Date.now(),
  resolution: '60',
  countBack: 24,
})

if (bars.meta.state === 'warming') {
  // Agg is preparing the series: call again after bars.meta.retryAfterMs.
}
```

`data` can be empty while Agg prepares a series. Read `meta.state`, and while it is `warming`, call again after `meta.retryAfterMs`.

## Keeping what recovery needs

`deposit`, `buy`, `sell` and `withdraw` can fail with the outcome unknown: the transfer, fill or withdrawal may exist even though the call failed. Following it instead of sending it again takes values that exist only while the call runs, and your app needs them after a reload or restart too. The SDK doesn't persist them, and a variable or a log line doesn't survive a reload. Store them in durable storage your app owns, such as your backend, **before** the call:

| Helper | Store | To |
| - | - | - |
| `deposit` | `idempotencyKey`, `chainId`, `token` and `amount` | Retry the same deposit with the same key |
| `buy`, `sell` | `quoteId`, from the `FILLING` progress event, and `mode` | Follow the fill with `getOrder(quoteId, { mode })` |
| `withdraw` | `requestId` and the withdrawal's parameters | Follow the withdrawal, or send `createWithdrawal` again with the same `requestId` |

The examples below use this interface for that storage. Implement it with your app's own persistence:

```typescript theme={null}
/** Durable storage your app owns. The SDK does not persist recovery data. */
interface PendingOperationStore {
  save(key: string, value: Record<string, string>): Promise<void>
  remove(key: string): Promise<void>
}
```

## Funding the Agg balance

Trades draw from the user's Agg balance. `deposit` sends a token from the Portal wallet to the user's Agg deposit address. It waits for the deposit addresses, then sends the transfer and resolves once it's broadcast. Agg credits it once it confirms. Once the transfer confirms, call `getBalances({ sync: true })` to re-read the chains.

> [!NOTE]
>
> The aggregate balance is not how much a user can spend on one trade. Spendability depends on which chain holds the funds. See [Balances are per chain, not one pot](https://docs.portalhq.io/integrations/Trading/agg.md#balances-are-per-chain-not-one-pot).

> [!TIP]
>
> If you show a deposit address yourself, read it with `getDepositAddresses()` right before you show it. Agg can reassign the deposit wallet of an inactive user, so a cached address can go stale. `deposit` reads it on every call.

This example uses the `PendingOperationStore` from [Keeping what recovery needs](#keeping-what-recovery-needs):

```typescript theme={null}
import { generateIdempotencyKey } from '@portal-hq/web'

const fundAgg = async (store: PendingOperationStore) => {
  const pending = {
    idempotencyKey: generateIdempotencyKey(),
    chainId: 'eip155:137',
    token: 'USDC',
    amount: '10',
  }
  const storeKey = `agg-deposit:${pending.idempotencyKey}`

  // Persist before sending, so this same deposit can be retried with its key
  // after DepositOutcomeUnknown or a restart.
  await store.save(storeKey, pending)

  const deposit = await agg.deposit(pending)

  // Broadcast: from here on, the transaction hash identifies the transfer.
  // A failed store write must not turn a sent deposit into an error.
  await store.remove(storeKey).catch(() => undefined)
  console.log(deposit.txHash, deposit.token.address)
}
```

When `deposit` fails, keep the stored record until you know the outcome. Remove it only after one of the failures below that send nothing.

`token` is the token's contract address or its symbol, as Agg lists it for `chainId`. A symbol is a convenience and isn't guaranteed to be unique. If it matches more than one token on the chain, `deposit` fails with `AmbiguousDepositToken` and sends nothing. Pass the address of one of `details.candidates` instead.

`deposit` sends nothing and fails with:

* `UnsupportedDepositToken` when Agg doesn't take the token on that chain
* `AmbiguousDepositToken` when the symbol matches several tokens
* `DepositAddressesTimeout` when the deposit addresses aren't ready in time
* `MissingRpcUrl` when `chainId` has no RPC URL configured
* `InvalidAmount` when `amount` isn't positive or has more decimals than the token, not counting trailing zeros

An `idempotencyKey` Portal can't use is rethrown unchanged, as a `PortalIdempotencyError`, before anything is sent.

### When a deposit's outcome is unknown

If the transfer fails after it starts sending, `deposit` fails with `DepositOutcomeUnknown`: the transfer may or may not have been broadcast. `details` carries the `idempotencyKey`, `chainId`, `depositAddress`, `token` and `amount`.

1. **Check whether the transfer went out** before sending it again, for example on the chain. A transfer missing from `listActivity({ type: 'deposit' })` or from the balance may not be credited yet, so neither proves it wasn't broadcast.
2. **To retry, call `deposit` again with `details.idempotencyKey`**, or after a restart, with the record you stored. While Portal remembers the key, at least 24 hours after the request was last updated, it won't broadcast a second transfer under it. It may refuse the retry instead: the refusal is the new error's `cause`, recognized by `isIdempotencyRejection`. See [Handle a rejection](https://docs.portalhq.io/sdks/web/guide/idempotency-keys.md#handle-a-rejection) for what each refusal means.
3. **Use a new key only once you've confirmed the first transfer didn't land and can no longer land.**

> [!WARNING]
>
> When you don't pass `idempotencyKey`, `deposit` generates a new key on every call, so calling it again without the key from the error sends a second transfer. A retry with the same key can also be refused with `IDEMPOTENCY_KEY_REUSED`, because `deposit` rebuilds the transfer on every call. This happens most often on Solana, and when Agg has issued a new deposit address.

## Buying and selling

`buy` and `sell` quote an outcome across venues, fill the quote at once and wait for the fill to finish. `buy` takes the USD to spend as `amount`; `sell` takes the number of `shares`.

This example uses the `PendingOperationStore` from [Keeping what recovery needs](#keeping-what-recovery-needs):

```typescript theme={null}
import { AggError, AggErrorReason, type AggMode } from '@portal-hq/web'

const buyOutcome = async (store: PendingOperationStore) => {
  const mode: AggMode = 'live' // 'paper' simulates the trade
  let storeKey: string | undefined
  let saving: Promise<void> = Promise.resolve()

  try {
    const { quote, status } = await agg.buy({
      outcomeId,
      amount: '5',
      slippageBps: 100,
      mode,
      onProgress: (event) => {
        // The quoteId exists before the fill request is sent: persist it with the mode.
        if (event.step === 'FILLING' && event.quote) {
          storeKey = `agg-fill:${event.quote.quoteId}`
          // onProgress can't wait for the store. A failed save is written again below.
          saving = store
            .save(storeKey, { quoteId: event.quote.quoteId, mode })
            .catch(() => undefined)
        }
      },
    })

    // The fill reached a final state, so there is nothing left to follow.
    // A failed store write must not turn a completed trade into an error.
    await saving
    if (storeKey) {
      await store.remove(storeKey).catch(() => undefined)
    }
    console.log(quote.quoteId, status.overallState) // 'filled' or 'partially_filled'
  } catch (error) {
    await saving
    if (AggError.is(error, AggErrorReason.OrderOutcomeUnknown)) {
      // The fill may exist: keep its record and never buy again. The error carries the quoteId even if this save fails.
      const { quoteId } = error.details.quote
      await store.save(`agg-fill:${quoteId}`, { quoteId, mode }).catch(() => undefined)
    } else if (storeKey) {
      // Nothing was traded, or the fill already ended: there is nothing left to follow.
      await store.remove(storeKey).catch(() => undefined)
    }
    throw error
  }
}
```

`onProgress` isn't awaited, so the save may still be running when the fill request is sent. `OrderOutcomeUnknown` also carries the `quoteId`, so the example saves it again there and rethrows the error: show the trade as pending and follow it with `getOrder(quoteId, { mode })` as described below. Never call `buy` or `sell` again for it.

After a restart, follow each stored record: call `getOrder(quoteId, { mode })` until its `terminal` is `true`, waiting `pollAfterMs` between reads when Agg sends it, then remove the record. If the fill request never reached Agg, what `getOrder` returns for that quote isn't specified: treat an error there as unknown rather than as nothing traded, and check `listOrders({ quoteId, mode })` before trading again.

The result holds the `quote`, the `fill`, and the final read of the order as `status`. Its `overallState` and `orders[]` tell you how much filled.

| `reason` | What happened | What to do |
| - | - | - |
| `QuoteNotTradable` | The quote isn't `ok`, or a venue reported a warning. Nothing was traded. `details.quote` holds the quote. | Show why, or quote again with different `venues` or a different amount. |
| `OrderFailed` | The fill ended in a final state other than `filled` or `partially_filled`. `details.status` is the final read, with `errorReason`. | Show the reason. |
| `OrderOutcomeUnknown` | The fill may have been placed, but the helper couldn't see it finish. | Poll `getOrder(details.quote.quoteId, { mode })` with the mode you traded in. Never call `buy` or `sell` again for it. |

Pass `mode: 'paper'` to simulate the trade, and `venues` to restrict routing to some venues. `getOrder` reads live orders unless you pass `{ mode: 'paper' }`, so a paper fill is only found when you pass the same mode. The quote doesn't record its mode: keep the one you traded in.

To show the user a price before they confirm, call the route methods yourself: `createQuote`, then `createOrder({ quoteId })`, then poll `getOrder(quoteId)`, passing the same `mode` to each. Before offering a quote, check that its `status` is `ok` and that it has no `warnings`. Quotes expire quickly; see [Trading](https://docs.portalhq.io/integrations/Trading/agg.md#trading) on the integration page.

## Limit orders

`placeLimitOrder` places a resting order on one venue from a decimal price and size. Pass the market's `venue` and the outcome's id.

```typescript theme={null}
const order = await agg.placeLimitOrder({
  venue: market.venue,
  venueMarketOutcomeId: outcomeId,
  side: 'buy',
  price: '0.2', // USD per share, below 1
  shares: '10',
})

// Cancel it with its orderId, not the quoteId.
await agg.cancelOrder({ orderId: order.orderId })
```

* `price` is USD per share, below `1`, with at most 6 decimals, not counting trailing zeros. `shares` also takes at most 6 decimals, not counting trailing zeros. Size orders in multiples of the market's `sizeStepRaw` and at least its `minSizeRaw`, which `getOrderbooks` returns.
* `timeInForce` defaults to `GTC`. `expiresAt` is required with `GTD`.
* `listOrders({ orderType: 'limit' })` lists the user's limit orders. Cancel an open one by its `id`.

A failure without a definite answer may still have placed the order. Check `listOrders` before placing it again.

> [!WARNING]
>
> Polymarket's \$1 minimum for orders that trade at once (price × shares) is applied after submission: `placeLimitOrder` resolves, and the order later fails, with the reason in `errorMessage` on `listOrders`. Check price × shares before submitting.

## Redeeming winnings

`listPositions` lists the user's positions. Once a market resolves, `redeemAll` redeems every position whose `redeemStatus` is `eligible`, and returns one result per batch of up to 20. Holdings on a losing outcome are left out, and the list is empty when nothing is eligible.

```typescript theme={null}
const results = await agg.redeemAll()

for (const batch of results) {
  console.log(batch.redeemId, batch.results)
}
```

`redeemAll` redeems live positions only, not paper ones. It stops at the first failure or abort: the call rejects, and the results of the batches before it, which may have redeemed, aren't returned. Read `listPositions` again before you redeem again.

To redeem specific positions, call `redeemPositions({ venueMarketOutcomeIds })` with up to 20 ids of positions whose `redeemStatus` is `eligible`. It takes the venue's own outcome id: `venueMarket.venueMarketOutcomes[].venueBreakdown[].venueMarketOutcomeId` on a position from `listPositions`. That is not the `venueMarketOutcomes[].id` you quote and trade with, which `placeLimitOrder` also calls `venueMarketOutcomeId`, and it can't be derived from an order.

## Withdrawing

`withdraw` withdraws from the Agg balance to a chain and waits for the withdrawal to finish. It previews the withdrawal first, and sends nothing unless the preview's `pricingStatus` is `quoted`.

This example uses the `PendingOperationStore` from [Keeping what recovery needs](#keeping-what-recovery-needs):

```typescript theme={null}
import { AggError, AggErrorReason } from '@portal-hq/web'

const withdrawToBase = async (store: PendingOperationStore) => {
  const pending = {
    requestId: crypto.randomUUID(),
    amount: '5',
    tokenSymbol: 'USDC',
    destinationChainId: 'eip155:8453',
  }
  const storeKey = `agg-withdrawal:${pending.requestId}`

  // Persist before calling, so a withdrawal that may exist can be followed
  // after WithdrawalOutcomeUnknown or a restart.
  await store.save(storeKey, pending)

  try {
    const withdrawal = await agg.withdraw(pending)

    // A failed store write must not turn a finished withdrawal into an error.
    await store.remove(storeKey).catch(() => undefined)
    console.log(withdrawal.withdrawalId, withdrawal.status) // 'completed' or 'partial'
  } catch (error) {
    if (!AggError.is(error, AggErrorReason.WithdrawalOutcomeUnknown)) {
      // Nothing was created, or the withdrawal already ended: there is nothing left to follow.
      await store.remove(storeKey).catch(() => undefined)
    }
    throw error
  }
}
```

* `destinationAddress` defaults to the user's own Portal address on that chain. Any other address must be on your environment's destination allowlist for Agg; see [Withdrawals](https://docs.portalhq.io/integrations/Trading/agg.md#withdrawals).
* To find the most the user can withdraw to a chain, call `quoteWithdrawable({ tokenSymbol, destinationChainId })`.
* A `partial` withdrawal succeeds. Read `completedAmountRaw` for what arrived.
* `withdraw` retries creating the withdrawal itself. When that request fails with a 429, 502, 503 or 504, or gets no answer, it sends the same request again, with the same `requestId`, for up to 3 attempts in all, 1 second and then 2 seconds apart. If every attempt was refused with a 4xx, such as a 429, `withdraw` rejects with the last error, not `WithdrawalOutcomeUnknown`. If any attempt failed with a 5xx or got no answer, it fails with `WithdrawalOutcomeUnknown`.

| `reason` | What happened | What to do |
| - | - | - |
| `WithdrawalNotViable` | The preview isn't `quoted`. Nothing was sent. `details.preview` holds it. | Show why, or try a different amount or chain. |
| `WithdrawalFailed` | The withdrawal ended `failed`. `details.withdrawal` holds it. | Show `errorMessage`. |
| `WithdrawalOutcomeUnknown` | The withdrawal may exist. | Follow `details`, and never call `withdraw` again for it. See below. |

Any other failure leaves no withdrawal to follow, so the example removes the stored record. Before the `WITHDRAWING` progress step nothing was sent, as with `WithdrawalNotViable`, `InvalidAmount`, an abort or `AGG_LINK_REQUIRED`. After it, the withdrawal either ended `failed` or every attempt to create it was refused. A record left behind would be resent with `createWithdrawal`, which skips the preview.

After `WithdrawalOutcomeUnknown`:

* **With `details.withdrawal`**, the withdrawal was created: poll `getWithdrawal(details.withdrawal.withdrawalId)`.
* **Without it**, creating the withdrawal got no definite answer: send `createWithdrawal(details.request)` again, then poll it. Its `requestId` makes Agg return the original withdrawal instead of creating a second one. Don't call `withdraw` again: it previews first, and the preview can refuse funds already on their way.

`requestId` is a UUID. When you don't pass one, `withdraw` generates a new one on every call. To recover after the app restarts, pass your own and store it with the withdrawal's parameters before calling, as the example above does. If the withdrawal may then exist, send `createWithdrawal` with the stored request (this `requestId`, the same parameters and the amount in base units as `amountRaw`).

> [!WARNING]
>
> If the first request never reached Agg, `createWithdrawal()` creates the withdrawal now, without the preview `withdraw()` runs first. How long Agg keeps returning the original withdrawal for a `requestId` isn't documented, so resume promptly, and check `getWithdrawal()` or `listActivity({ type: 'withdrawal' })` before sending a stored request that is days old.

## Progress, cancellation and reconnecting

`deposit`, `buy`, `sell`, `placeLimitOrder`, `redeemAll` and `withdraw` take these options:

| Option | Type | Description |
| - | - | - |
| `onProgress` | `(event: AggProgress) => void` | Called at each step. A callback that throws is logged and never stops the helper. |
| `autoReconnect` | `boolean` | On `AGG_LINK_REQUIRED`, run `connect` on the chain of the last successful `connect` and retry that call once. Until `connect` has succeeded on this `Portal` instance, for example after a page reload, that chain is Polygon (`eip155:137`), which then needs an RPC URL. Defaults to `false`. Calls refused together share one `connect`, so the user signs once. |
| `signal` | `AbortSignal` | Stops the helper. See below. |

```typescript theme={null}
const controller = new AbortController()

const result = await agg.buy({
  outcomeId,
  amount: '5',
  autoReconnect: true,
  signal: controller.signal,
  onProgress: (event) => {
    console.log(event.step) // e.g. 'QUOTING', 'FILLING', 'POLLING_ORDER'
  },
})
```

The steps are `RECONNECTING`, `AWAITING_DEPOSIT_ADDRESSES`, `SENDING_DEPOSIT`, `DEPOSIT_SENT`, `QUOTING`, `FILLING`, `POLLING_ORDER`, `PLACING_ORDER`, `REDEEMING`, `PREVIEWING_WITHDRAWAL`, `WITHDRAWING` and `POLLING_WITHDRAWAL`. Each event also carries what the helper has learned so far, such as `quote`, `fill`, `order`, `txHash`, `idempotencyKey`, `withdrawalPreview` or `withdrawal`.

**Aborting.** Before anything is sent, an aborted helper rejects with the abort reason. A request already sent is never abandoned or repeated:

* A fill or withdrawal that may exist ends in `OrderOutcomeUnknown` or `WithdrawalOutcomeUnknown`, carrying its ids.
* A deposit that has started sending still resolves with its result.

**Waiting.** `buy`, `sell` and `withdraw` wait for the outcome, and `deposit` waits for the deposit addresses. Each takes a poll option with `intervalMs` and `timeoutMs`: `poll` on `buy`, `sell` and `withdraw`, and `addressPoll` on `deposit`. If the wait times out, `buy`, `sell` and `withdraw` fail with their outcome-unknown error, and `deposit` with `DepositAddressesTimeout`.

| Wait | Default |
| - | - |
| Deposit addresses (`addressPoll`) | Every 2 seconds, up to 60 seconds |
| A fill (`poll` on `buy` and `sell`) | Every second, up to 3 minutes. When Agg sends `pollAfterMs`, it is used instead of `intervalMs`, kept between 250 milliseconds and 10 seconds. `timeoutMs` always applies. |
| A withdrawal (`poll` on `withdraw`) | Every 5 seconds, up to 10 minutes |

While polling, a helper reads through up to 5 transient failures in a row. Each request gives up after 120 seconds without an answer, failing with `AggNoResponseError`.

## Handling errors

Most Agg failures are one of three kinds:

* **`AggError`**: a request the SDK refused to send, or a helper outcome. Branch on `reason` with `AggError.is(error, reason)`. `details` holds the context of each reason.
* **A failed request**: the Portal API answered with an error. Read it with `AggApiError.from(error)`, which gives the HTTP `status`, Portal's `id`, the `message`, Agg's `code` and `fields` when Agg declined the request, and the `traceId` to quote to Portal support. It also unwraps the cause of an `OrderOutcomeUnknown` or `WithdrawalOutcomeUnknown`.
* **`AggNoResponseError`**: the Portal API sent no usable answer, so the request may or may not have been processed. It carries a `traceId`. Check for it before calling `AggApiError.from`, which also accepts it but returns only the `traceId`.

Other errors pass through unchanged: the signal's abort reason, a `PortalIdempotencyError` for an `idempotencyKey` Portal can't use, a credential that couldn't be resolved, and a rejected signature approval in `connect`. `AggApiError.from` returns `undefined` for all of them. A signing failure in the Portal iframe, such as an MPC error or a policy rejection, also passes through as a `PortalMpcError` or `PortalPolicyError`, and `AggApiError.from` wraps it like a failed request.

```typescript theme={null}
import { AggApiError, AggError, AggErrorId, AggNoResponseError } from '@portal-hq/web'

try {
  await agg.placeLimitOrder({
    venue: market.venue,
    venueMarketOutcomeId: outcomeId,
    side: 'buy',
    price: '0.2',
    shares: '10',
  })
} catch (error) {
  if (AggError.is(error)) {
    console.error(error.reason, error.details)
  } else if (error instanceof AggNoResponseError) {
    // The order may have been placed: check listOrders({ orderType: 'limit' }) before placing it again.
    console.error('No response from the Portal API', error.traceId)
  } else {
    const apiError = AggApiError.from(error)

    if (apiError?.id === AggErrorId.LinkRequired) {
      await agg.connect() // then retry
    } else if (apiError?.isRateLimit) {
      // wait, then retry
    } else if (apiError) {
      console.error(apiError.status, apiError.message, apiError.traceId)
    } else {
      throw error
    }
  }
}
```

`AggErrorId` holds the ids Portal returns for Agg requests:

| `AggErrorId` | `id` | What to do |
| - | - | - |
| `LinkRequired` | `AGG_LINK_REQUIRED` | Run `connect`, then retry. |
| `AccountAbstractionUnsupported` | `AGG_ACCOUNT_ABSTRACTION_UNSUPPORTED` | The client is account-abstracted and can't link or trade. |
| `SessionRefreshInProgress` | `AGG_SESSION_REFRESH_IN_PROGRESS` | Another request is renewing the user's Agg session. The SDK retries any Agg call that gets it up to 3 times, after 0.5, 1 and 2 seconds, before returning it. |
| `IntegrationResponseSchemaDrift` | `INTEGRATION_RESPONSE_SCHEMA_DRIFT` | Agg changed a response shape and Portal has to adapt. A trade or withdrawal may still have happened. |

When Agg declines a request, the error has no `id`, Agg's HTTP status, and a message starting with `Agg rejected the request`. A 403 on a trading route usually means the user's location is blocked. `AggApiError.from` returns `undefined` for a value that isn't a failed Agg request, such as a credential failure.

The `AggError` reasons that come before anything is sent are `NoAddress`, `MissingRpcUrl`, `AddressMismatch`, `EmptyIdentifier` (a blank id that would reach a different route) and `InvalidAmount` (an amount, price or size that isn't positive, has too many decimals, or a price of 1 or more), plus the deposit, trade and withdrawal reasons described above.

## Low-level APIs

Each Portal API route, except self-custody signature submission (`POST /orders/{quoteId}/signatures`), has a route method that resolves with its response as `{ data }`. A failed request rejects with the Portal API error, which you read with `AggApiError.from`, or with `AggNoResponseError`. See the [endpoint reference](https://docs.portalhq.io/integrations/Trading/agg.md#endpoint-reference) for each route.

| Group | Methods |
| - | - |
| Link | `createLinkChallenge`, `createLink`, `getLink`, `deleteLink` |
| Discovery | `listEvents`, `getEvent`, `getEventBootstrap`, `listMarkets`, `search`, `listCategories`, `getVenueGeoPolicy`, `getAppConfig` |
| Market data | `getMidpoints`, `getOrderbooks`, `getOutcomeOrderbook`, `getChartBars`, `getChartHistoryManifest` |
| Account | `getUser`, `getDepositAddresses`, `getBalances`, `listPositions`, `listOrders`, `listActivity` |
| Trading | `createQuote`, `createOrder`, `getOrder`, `createLimitOrder`, `createDirectOrder`, `cancelOrder`, `redeemPositions` |
| Withdrawals | `quoteWithdrawable`, `previewWithdrawal`, `createWithdrawal`, `getWithdrawal` |

`createLimitOrder` takes the price and size as integers scaled by 1e6, which `placeLimitOrder` does for you. `createDirectOrder` places a market order on one venue without a quote; its `externalId` must be unique per app and at most 36 characters, and a replay is refused with a 409 rather than trading twice.

## Limitations

* **No self-custody fills.** The SDK fills from the user's Agg balance. Pricing and filling against the user's own wallet ([Self-custody fills](https://docs.portalhq.io/integrations/Trading/agg.md#self-custody-fills)) isn't available in the Web SDK.
* **Webhooks** go directly from Agg to your backend; see [Webhooks](https://docs.portalhq.io/integrations/Trading/agg.md#webhooks).

## Next Steps

* Read the [Agg integration page](https://docs.portalhq.io/integrations/Trading/agg.md) for setup, geo restrictions and compliance.
* Use [idempotency keys](https://docs.portalhq.io/sdks/web/guide/idempotency-keys.md) to retry deposits safely.
* Learn about [signature approvals](https://docs.portalhq.io/sdks/web/guide/add-custom-signature-hooks.md) for the `connect` signature.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.