> ## 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 it, and buy, sell, redeem and withdraw on prediction markets with the React Native SDK.

Portal's React Native SDK lets your users trade prediction markets across Polymarket, Kalshi, Limitless and other venues through `portal.predictionMarkets.agg`. This guide covers discovering markets, linking the Portal wallet, funding the user's Agg balance, trading, redeeming and withdrawing, and recovering safely when the outcome of a request is unknown.

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

## Overview

With `portal.predictionMarkets.agg` you can:

* **Discover** events, markets and outcomes, with prices, order books and charts
* **Link** the Portal wallet to the user's Agg account with one signature
* **Fund** the user's Agg balance from the Portal wallet
* **Buy** and **sell** outcomes, and **place** and **cancel** limit orders
* **Redeem** winning positions and **withdraw** to a Portal address

The [Agg by Snag 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. Two kinds of method are available:

* **Helpers** (`connect`, `isConnected`, `deposit`, `buy`, `sell`, `placeLimitOrder`, `redeemAll` and `withdraw`) run a whole flow and resolve with its result.
* **API 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.

## Prerequisites

Before using Agg, ensure you have:

* The Agg by Snag integration set up for your environment (see [Setup](https://docs.portalhq.io/integrations/Trading/agg.md#setup))
* A properly initialized Portal client with a wallet (see [Getting started](https://docs.portalhq.io/sdks/react-native/guide/getting-started.md) and [Create a wallet](https://docs.portalhq.io/sdks/react-native/guide/create-a-wallet.md))
* A `gatewayConfig` entry for every chain the wallet signs or sends on. `connect` signs on Polygon (`eip155:137`) by default, and `deposit` sends on the chain you deposit from. The default `gatewayConfig` covers the [11 built-in chains](https://docs.portalhq.io/sdks/react-native/guide/getting-started.md#initializing-portal), Polygon included. A custom `gatewayConfig` is used exactly as supplied (see [Custom RPC configuration](https://docs.portalhq.io/sdks/react-native/guide/getting-started.md#custom-rpc-configuration)).
* Gas on the wallet for the chain you deposit from

> [!WARNING]
>
> **Everything except discovery and market data requires a Portal client *without* [account abstraction](https://docs.portalhq.io/resources/account-abstraction.md).** Agg signs users in with a signature from the wallet's own key. For an account-abstracted client, the Portal API rejects every link, account, trading, redemption and withdrawal call with `AGG_ACCOUNT_ABSTRACTION_UNSUPPORTED`. That includes `isConnected()`, which throws instead of returning `false`, and the helpers built on those calls. Discovery and market data (events, markets, search, categories, geo policy, app config, midpoints, order books and charts) still work.

> [!WARNING]
>
> **Live trading is real money and geo-restricted.** Every venue blocks some countries, and geofencing your users 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 go live.

The examples in this guide use a `portal` instance:

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

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

const agg = portal.predictionMarkets.agg
```

## Discovering markets

Agg models prediction markets as events, markets and outcomes (see [Markets, events and outcomes](https://docs.portalhq.io/integrations/Trading/agg.md#markets-events-and-outcomes)). You trade an **outcome**, identified by `venueMarketOutcomes[].id` on a market. Discovery works before the wallet is linked.

```typescript theme={null}
const { data: page } = await agg.listEvents({
  status: 'open',
  sortBy: 'volume24hr',
  sortDir: 'desc',
  limit: 10,
})

for (const event of page.data) {
  for (const market of event.venueMarkets ?? []) {
    for (const outcome of market.venueMarketOutcomes) {
      console.log(`${event.title} · ${market.question} · ${outcome.label}: ${outcome.id}`)
    }
  }
}

// Lists are paginated: pass nextCursor as cursor while hasMore is true.
if (page.hasMore && page.nextCursor) {
  const { data: next } = await agg.listEvents({ cursor: page.nextCursor })
  console.log(`Loaded ${next.data.length} more events`)
}
```

Use `search({ q, type: 'events' | 'markets' })` for free-text search, and `getEvent(eventId)` for one event. For prices, read `getMidpoints(venueMarketIds)`, `getOutcomeOrderbook(outcomeId, { depth })` and `getChartBars({ venueMarketOutcomeId, to })`. Every method is listed in [Low-level APIs](#low-level-apis).

## Linking the wallet

Before a user can fund or trade, link their Portal wallet to their Agg account with `connect()`. It requests a Sign-In with Ethereum challenge, signs it with `personal_sign` on Polygon, and completes the link.

```typescript theme={null}
const link = await agg.connect()
console.log(`✅ Linked ${link.linkedAddress} to Agg user ${link.aggUserId}`)
```

`connect(chainId?)` signs on another EVM chain Agg supports when you pass its CAIP-2 ID. Nothing is signed when:

* the chain has no `gatewayConfig` entry (`MissingRpcUrl`),
* the client has no EVM address (`NoAddress`), or
* the challenge names an address other than the wallet's own (`AddressMismatch`).

With [custom signature hooks](https://docs.portalhq.io/sdks/react-native/guide/add-custom-signature-hooks.md), the link signature reaches your `portal_signingRequested` handler as a normal `personal_sign` request.

### When the link expires

Portal keeps the user's Agg session and refreshes it, but it can still expire. Any linked call then fails with `AGG_LINK_REQUIRED`, and the fix is to run `connect()` again.

`isConnected()` returns whether the client is linked, and `false` can also mean the session expired. Don't rely on it alone: a call can still fail with `AGG_LINK_REQUIRED` after it returns `true`. Instead, pass `autoReconnect: true` to the helpers. On `AGG_LINK_REQUIRED`, a helper runs `connect()` and retries the refused call once. It links on the chain of the last successful `connect()` on this `Portal` instance, or on Polygon when there hasn't been one, for example after the app restarts. Helpers refused together share one `connect()`, so the user signs once. A call refused for the link did nothing, so the retry can't trade or send twice.

`autoReconnect` applies to helpers only. The [low-level APIs](#low-level-apis) reject with `AGG_LINK_REQUIRED` and leave reconnecting to you. To unlink, call `deleteLink()`.

## 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. To follow it instead of sending it again, your app needs values that exist only while the call runs, and it needs them after a crash or restart too. The SDK doesn't persist them. Store them in durable storage your app owns, such as a database or encrypted storage, **before** the call that can create the operation:

| Operation | 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 parameters | Follow the withdrawal, or send `createWithdrawal()` again with the same `requestId` |

The examples in this guide 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. */
export interface PendingOperationStore {
  save(key: string, value: Record<string, string>): Promise<void>
  remove(key: string): Promise<void>
}
```

Following an operation means polling it until it reaches a final state. Retry only transient failures, back off between attempts, and stop at a deadline while keeping the stored values, so you can check again later. The recovery examples use these helpers:

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

export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

/** No response, a rate limit or a gateway error: worth reading again. */
export const isTransientAggError = (error: unknown): boolean =>
  error instanceof AggNoResponseError ||
  [429, 502, 503, 504].includes(AggApiError.from(error)?.status ?? 0)
```

## Funding the Agg balance

`deposit()` sends a token from the Portal wallet to the user's Agg deposit address and resolves once the transfer is broadcast. It waits for the deposit addresses, since Agg creates them after the first link.

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

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

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

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

  const result = await agg.deposit({
    ...pending,
    autoReconnect: true,
    onProgress: (event) => console.log(event.step),
  })

  // Broadcast: from here on, the transaction hash identifies the transfer.
  await store.remove(storeKey)
  console.log(`✅ Sent ${result.token.symbol} in ${result.txHash}`)
}
```

When `deposit()` fails, keep the stored record until you know the outcome. Remove it only after a failure that means nothing was sent (see the note at the end of this section).

The parameters:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `chainId` | `string` | Yes | The CAIP-2 chain to send from. It must be one of the deposit addresses' `supportedChains`. |
| `token` | `string` | Yes | The token's contract address (an EVM address in any case; any other address, such as a Solana mint, exactly) or its symbol in any case, such as `USDC`. |
| `amount` | `string` | Yes | A positive decimal string, such as `"10"` or `"1.5"`. |
| `idempotencyKey` | `string` | No | The key the transfer is sent with. When omitted, the SDK generates a new one on every call. |
| `addressPoll` | `AggPollOptions` | No | How to wait for the deposit addresses. Defaults to every 2 seconds, for up to 60 seconds. |

`deposit()` also takes the [helper options](#progress-cancellation-and-timeouts). It resolves with `{ txHash, depositAddress, chainId, token, idempotencyKey }`, where `token` is the token as Agg lists it on `chainId`. Agg credits the deposit once the transfer confirms. To see it, read `getBalances({ sync: true })`.

### Choosing the token

A token is identified by its chain and address. A symbol is only a convenience, and one symbol can name several tokens on the same chain. `deposit()` never picks one by position:

* When `token` names no token Agg takes on `chainId`, it fails with `UnsupportedDepositToken`.
* When `token` names more than one, it fails with `AmbiguousDepositToken`. `error.details.candidates` lists the matches, with their `symbol`, `address` and `decimals`: pass the `address` of the one to send.
* When Agg lists the same address more than once with different `decimals`, it also fails with `AmbiguousDepositToken`, and the candidates share one address. Passing that address fails the same way, so the token can't be deposited until Agg's listing is corrected.

Nothing is sent in any of these cases.

### When the outcome of a deposit is unknown

Once the transfer has started, any failure to get its transaction hash is `DepositOutcomeUnknown`: the transfer may or may not have been broadcast. `error.details` carries the `idempotencyKey`, `chainId`, `depositAddress`, `token` and `amount`, and `error.cause` is the underlying failure.

`DepositOutcomeUnknown` is deliberately conservative. The SDK raises it for every failure after it starts building the transfer, including failures from before anything is signed, for example when Portal can't build the transaction. Read `error.cause` to tell these apart. `error.details.token` is the token the first attempt resolved to, so retry with `token: error.details.token.address`.

1. **Check whether the transfer went out**, 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. **Retry only with the same `idempotencyKey`** until you've confirmed the first transfer didn't land. While Portal remembers the key, for at least 24 hours after the request was last updated, it won't broadcast a second transfer under it.
3. **Read the retry's refusal from `error.cause`.** Portal can refuse the retry with an [idempotency rejection](https://docs.portalhq.io/sdks/react-native/guide/idempotency-keys.md#handle-a-rejection), which arrives as the `cause` of a new `DepositOutcomeUnknown`.

```typescript theme={null}
import { AggError, AggErrorReason } from '@portal-hq/core'
import {
  isIdempotencyRejection,
  PortalIdempotencyErrorId,
  type PortalMpcError,
} from '@portal-hq/utils'

const retryDeposit = async (pending: {
  idempotencyKey: string
  chainId: string
  token: string
  amount: string
}) => {
  try {
    return await agg.deposit(pending)
  } catch (error) {
    if (
      AggError.is(error, AggErrorReason.DepositOutcomeUnknown) &&
      isIdempotencyRejection(error.cause)
    ) {
      const { id } = error.cause as PortalMpcError

      switch (id) {
        case PortalIdempotencyErrorId.RequestInProgress:
          console.log('⏳ Still processing. Retry later with the same key.')
          break
        case PortalIdempotencyErrorId.RequestAlreadyCompleted:
          console.log('✅ Already broadcast. Don’t send it again.')
          break
        default:
          console.log(`⚠️ Unconfirmed (${id}). Check the chain before sending under a new key.`)
      }
      return undefined
    }
    throw error
  }
}
```

> [!WARNING]
>
> `deposit()` rebuilds the transfer on every call, so Portal can refuse a retry with `IDEMPOTENCY_KEY_REUSED` when the rebuilt transfer differs. This is usual on Solana, whose transactions carry a new recent blockhash, and when Agg has issued a new deposit address. Send under a new key only once you've confirmed the first transfer didn't land and can no longer land. For a deposit older than 24 hours, check the chain before retrying with any key.

> [!NOTE]
>
> Failures before the transfer starts, such as `MissingRpcUrl`, `UnsupportedDepositToken`, `AmbiguousDepositToken` or `DepositAddressesTimeout`, mean nothing was sent. An `idempotencyKey` that Portal can't accept is also rethrown unchanged, as a `PortalIdempotencyError`, because it is refused before anything is signed.

> [!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.

## Buying and selling

`buy()` and `sell()` quote an outcome, fill the quote at once, and wait for the fill to finish. They resolve with `{ quote, fill, status }`, where `status` is the final read of the fill. `status.overallState` is `filled` or `partially_filled`, and `status.orders` says how much filled.

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

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

const buyOutcome = async (
  store: PendingOperationStore,
  outcomeId: string,
  mode: AggMode = 'live',
) => {
  const storeKeys: string[] = []
  const saves: Promise<void>[] = []

  let result: AggTradeResult
  try {
    result = await agg.buy({
      outcomeId,
      amount: '5', // USD to spend
      slippageBps: 100,
      mode,
      autoReconnect: true,
      onProgress: (event) => {
        if (event.step === 'FILLING' && event.quote) {
          // The fill is about to be sent: keep what following it would need.
          const storeKey = `agg-fill:${event.quote.quoteId}`
          storeKeys.push(storeKey)
          // onProgress can't wait for the store, so keep the promise and settle it below.
          saves.push(store.save(storeKey, { quoteId: event.quote.quoteId, mode }))
        }
        // Each execution step carries a label that is ready to show.
        event.order?.steps.forEach((step) => console.log(step.label))
      },
    })
  } catch (error) {
    // A failed save must never replace the error from buy().
    await Promise.allSettled(saves)
    if (!AggError.is(error, AggErrorReason.OrderOutcomeUnknown)) {
      // Nothing was traded, or the fill already ended: there is nothing left to follow.
      await Promise.allSettled(storeKeys.map((storeKey) => store.remove(storeKey)))
    }
    throw error
  }

  // The fill reached a final state, so there is nothing left to follow.
  await Promise.allSettled(saves)
  await Promise.allSettled(storeKeys.map((storeKey) => store.remove(storeKey)))
  console.log(`✅ ${result.status.overallState} for quote ${result.quote.quoteId}`)
}

const sellOutcome = async (outcomeId: string) => {
  const { status } = await agg.sell({ outcomeId, shares: '3' })
  console.log(`✅ ${status.overallState}`)
}
```

`onProgress` can't delay the helper, so the save above may still be running when the fill request is sent. `OrderOutcomeUnknown` also carries the `quoteId`, so save it again there, as the next example does.

| Parameter | Type | Required | Description |
| - | - | - | - |
| `outcomeId` | `string` | Yes | `venueMarketOutcomes[].id` of a market. |
| `amount` | `string` | `buy` only | The USD to spend, as a decimal string. Venue minimums are counted in shares. |
| `shares` | `string` | `sell` only | The shares to sell, as a decimal string. |
| `slippageBps` | `number` | No | The slippage tolerance, in basis points. |
| `venues` | `AggVenue[]` | No | Restrict routing to these venues, for example `['polymarket']`. |
| `mode` | `'live' \| 'paper'` | No | `paper` asks Agg for a simulated trade against a paper balance (`PAPER_USD`) instead of real funds. Pass the same `mode` to `getOrder`, `listOrders`, `listPositions` and `getBalances` to read paper results. Confirm with Snag that paper trading is available for your Agg app before you rely on it. |
| `poll` | `AggPollOptions` | No | `intervalMs` is how often to read the fill when Agg sends no `pollAfterMs` (default every second). When Agg sends one, it is used instead, kept between 250 milliseconds and 10 seconds. `timeoutMs` always applies (default 3 minutes). |

Both also take the [helper options](#progress-cancellation-and-timeouts). They fail with:

* **`QuoteNotTradable`**: the quote's `status` isn't `ok`, or a venue reported a warning. Nothing was traded. `error.details.quote` carries the `status`, `error` and `warnings`.
* **`OrderFailed`**: the fill ended in a final state other than `filled` or `partially_filled`. `error.details.status` is the final read, with `errorReason`.
* **`OrderOutcomeUnknown`**: the fill may exist, but the helper couldn't see it finish, for example after a timeout, an abort, a lost connection or a 5xx on the fill request.
* **An unchanged API error**: Portal or Agg refused the quote or the fill with a definite answer, such as a 4xx. Nothing was traded. A 403 on a trade usually means the user's location is blocked.

### When the outcome of a fill is unknown

After `OrderOutcomeUnknown`, **never call `buy()` or `sell()` again**: the first fill may still execute. Follow it with `getOrder(quoteId, { mode })` instead, using the same `mode` as the trade: neither the quote nor the error records it. `error.details` carries the `quote`, the `fill` when it was placed, and `last`, the last read of the fill.

This example uses `PendingOperationStore`, `sleep` and `isTransientAggError` from [Keeping what recovery needs](#keeping-what-recovery-needs):

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

/** Reads a fill until it is final, retrying transient failures, for up to `timeoutMs`. */
const followFill = async (
  quoteId: string,
  mode: AggMode,
  timeoutMs = 10 * 60 * 1000,
): Promise<AggExecutionStatus> => {
  const deadline = Date.now() + timeoutMs
  let waitMs = 1000

  while (Date.now() < deadline) {
    try {
      const { data: status } = await agg.getOrder(quoteId, { mode })
      if (status.terminal) {
        return status
      }
      waitMs = status.pollAfterMs ?? 1000
    } catch (error) {
      if (!isTransientAggError(error)) {
        throw error
      }
      waitMs = Math.min(waitMs * 2, 30 * 1000)
    }
    await sleep(waitMs)
  }

  throw new Error(`Quote ${quoteId} isn't final yet. Keep its quoteId and mode, and check again later.`)
}

const buyOnce = async (
  store: PendingOperationStore,
  outcomeId: string,
  amount: string,
  mode: AggMode,
) => {
  try {
    return (await agg.buy({ outcomeId, amount, mode })).status
  } catch (error) {
    if (!AggError.is(error, AggErrorReason.OrderOutcomeUnknown)) {
      throw error
    }

    // Follow the existing fill instead of trading again.
    const { quoteId } = error.details.quote
    const storeKey = `agg-fill:${quoteId}`
    await store.save(storeKey, { quoteId, mode })

    const status = await followFill(quoteId, mode)
    await store.remove(storeKey)
    return status
  }
}
```

After a restart, call `followFill()` with each stored `quoteId` and `mode`.

When `error.details.fill` is absent, the fill request itself got no definite answer, so the fill may or may not exist. What `getOrder()` returns for a quote that was never filled isn't specified, so treat an error there as unknown, not as "nothing traded". Check `listOrders({ quoteId, mode })` and the user's activity before you trade again.

## Limit orders

`placeLimitOrder()` places a resting order from a decimal price and size, and resolves with the order once it is placed. Cancel it with `cancelOrder()` and its `orderId`.

```typescript theme={null}
const placeAndCancel = async (venueMarketOutcomeId: string) => {
  const order = await agg.placeLimitOrder({
    venue: 'polymarket',
    venueMarketOutcomeId,
    side: 'buy',
    price: '0.42', // USD per share
    shares: '10',
    timeInForce: 'GTC',
  })
  console.log(`✅ Order ${order.orderId} is ${order.status}`)

  const { data: cancelled } = await agg.cancelOrder({ orderId: order.orderId })
  console.log(`✅ Cancel ${cancelled.status}`)
}
```

| Parameter | Type | Required | Description |
| - | - | - | - |
| `venue` | `AggVenue` | Yes | The venue of the market. |
| `venueMarketOutcomeId` | `string` | Yes | `venueMarketOutcomes[].id` of a market on that venue. |
| `side` | `'buy' \| 'sell'` | Yes | The order side. |
| `price` | `string` | Yes | USD per share, below 1, with at most 6 decimals, for example `"0.2"`. |
| `shares` | `string` | Yes | Shares, with at most 6 decimals. |
| `timeInForce` | `AggTimeInForce` | No | `GTC` (the default), `GTD`, `FOK`, `FAK`, `IOC` or `ALO`. |
| `postOnly` | `boolean` | No | Place the order only if it rests on the book instead of trading at once. |
| `expiresAt` | `string` | With `GTD` | When the order expires. |
| `clientOrderId` | `string` | No | Your own ID for the order, returned on `listOrders()`. |

Before sending, the SDK checks only that `price` and `shares` are positive decimal strings with at most 6 decimal places, not counting trailing zeros, and that `price` is below 1. Anything else fails with `InvalidAmount`, and nothing is sent. The SDK doesn't check the market's tick size or minimum size; the venue enforces those.

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

Unlike `buy()` and `sell()`, `placeLimitOrder()` doesn't wait for the order to fill or classify an ambiguous failure. After an `AggNoResponseError` or a 5xx, the order may have been placed: check `listOrders({ orderType: 'limit' })` before placing it again.

## Redeeming winnings

`redeemAll()` redeems every live position whose `redeemStatus` is `eligible`, in batches of 20, and resolves with each batch's result. It skips holdings on a losing outcome, and resolves with an empty list when nothing is eligible. Paper positions are not included.

```typescript theme={null}
const redeem = async () => {
  const batches = await agg.redeemAll({ autoReconnect: true })

  for (const batch of batches) {
    for (const result of batch.results) {
      console.log(`${result.venueMarketOutcomeId}: ${result.status}`)
    }
  }
}
```

`redeemAll()` stops at the first failure or abort, and the results of batches that already went through are not returned. Check `listPositions()` and `listActivity({ type: 'redeem' })` before you run it 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 trade with, and it can't be derived from an order.

## Withdrawing

`withdraw()` moves funds out of the Agg balance and waits for the withdrawal to finish. It previews the withdrawal first and sends nothing unless the amount prices as `quoted`. It resolves with the withdrawal once its `status` is `completed` or `partial`.

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

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

const withdrawToBase = async (store: PendingOperationStore) => {
  const pending = {
    requestId: generateIdempotencyKey(), // a UUID
    amount: '10',
    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, a crash or a restart.
  await store.save(storeKey, pending)

  const withdrawal = await agg.withdraw({ ...pending, autoReconnect: true })

  await store.remove(storeKey)
  console.log(`✅ Withdrawal ${withdrawal.withdrawalId} is ${withdrawal.status}`)
}
```

| Parameter | Type | Required | Description |
| - | - | - | - |
| `amount` | `string` | Yes | A decimal string in `tokenSymbol`, with no more decimals than the token has. |
| `tokenSymbol` | `AggTokenSymbol` | Yes | The token to withdraw, for example `USDC`. |
| `destinationChainId` | `string` | Yes | The CAIP-2 chain to withdraw to. |
| `destinationAddress` | `string` | No | Defaults to the user's own Portal address on that chain. Any other address must be on your environment's [destination allowlist](https://docs.portalhq.io/integrations/Trading/agg.md#withdrawals). |
| `requestId` | `string` | No | A UUID that Agg uses to avoid creating the withdrawal twice. When omitted, a new one is generated on every call. |
| `poll` | `AggPollOptions` | No | How to read the withdrawal. Defaults to every 5 seconds, for up to 10 minutes. |

`withdraw()` also takes the [helper options](#progress-cancellation-and-timeouts). It fails with:

* **`WithdrawalNotViable`**: the preview didn't price as `quoted`. Nothing was sent. `error.details.preview` carries the `pricingStatus` and `unviableReason`.
* **`WithdrawalFailed`**: the withdrawal ended `failed`. `error.details.withdrawal` carries its `errorMessage`.
* **`WithdrawalOutcomeUnknown`**: the withdrawal may exist. Any failure after that point, an abort included, ends here.
* **An unchanged API error**: Portal or Agg refused the preview or the withdrawal with a definite answer, such as a 4xx. Nothing was withdrawn. A 403 here usually means `destinationAddress` isn't on your allowlist.

When creating the withdrawal fails with a rate limit, a gateway error or no response, `withdraw()` sends the same request again, with the same `requestId`, up to 3 attempts in all. If every attempt was refused with a rate limit (429), the 429 is rethrown unchanged: Agg refused each attempt, so nothing was created.

### When the outcome of a withdrawal is unknown

After `WithdrawalOutcomeUnknown`, **never call `withdraw()` again**. Without the same `requestId` it would create a second withdrawal, and with it, it would preview again, and the preview can refuse funds that are already on their way. Follow the existing withdrawal instead:

* With `error.details.withdrawal`, it was created: poll `getWithdrawal(withdrawalId)`.
* Without it, creating it got no definite answer: send `createWithdrawal(error.details.request)` again, then poll it. The request carries the same `requestId`, so Agg returns the original withdrawal instead of creating a second one.

This example uses `sleep` and `isTransientAggError` from [Keeping what recovery needs](#keeping-what-recovery-needs):

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

const FINAL_WITHDRAWAL_STATUSES = ['completed', 'partial', 'failed']

/** Follows a withdrawal that may exist until it is final, for up to `timeoutMs`. */
const followWithdrawal = async (
  error: unknown,
  timeoutMs = 30 * 60 * 1000,
): Promise<AggWithdrawal> => {
  if (!AggError.is(error, AggErrorReason.WithdrawalOutcomeUnknown)) {
    throw error
  }

  const deadline = Date.now() + timeoutMs
  let withdrawalId = error.details.withdrawal?.withdrawalId
  let waitMs = 5000

  while (Date.now() < deadline) {
    try {
      // Same requestId: Agg returns the original withdrawal instead of creating another.
      withdrawalId ??= (await agg.createWithdrawal(error.details.request)).data.withdrawalId

      const { data: latest } = await agg.getWithdrawal(withdrawalId)
      if (FINAL_WITHDRAWAL_STATUSES.includes(latest.status)) {
        return latest
      }
      waitMs = 5000
    } catch (followError) {
      if (!isTransientAggError(followError)) {
        throw followError
      }
      waitMs = Math.min(waitMs * 2, 60 * 1000)
    }
    await sleep(waitMs)
  }

  throw new Error(`Withdrawal ${error.details.request.requestId} isn't final yet. Keep it stored and check again later.`)
}
```

To resume after your app restarts, send `createWithdrawal()` with the request you stored: the same `requestId` (a UUID), `tokenSymbol`, `destinationChainId` and `destinationAddress`, and the amount in base units as `amountRaw`. `quoteWithdrawable({ tokenSymbol, destinationChainId })` returns the token's `decimals` for that destination. A `requestId` can't be combined with `max`.

> [!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 timeouts

Every helper except `connect` and `isConnected` takes 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`, link again and retry the refused call once. See [When the link expires](#when-the-link-expires). |
| `signal` | `AbortSignal` | Stops the helper. |

Each progress event carries a `step`, and the fields the helper knows at that point: `quote`, `fill`, `order`, `txHash`, `idempotencyKey`, `withdrawalPreview` and `withdrawal`.

| Helper | Steps |
| - | - |
| `deposit` | `AWAITING_DEPOSIT_ADDRESSES`, `SENDING_DEPOSIT` (with `idempotencyKey`), `DEPOSIT_SENT` (with `txHash`) |
| `buy`, `sell` | `QUOTING`, `FILLING`, `POLLING_ORDER` |
| `placeLimitOrder` | `PLACING_ORDER` |
| `redeemAll` | `REDEEMING`, once per batch |
| `withdraw` | `PREVIEWING_WITHDRAWAL`, `WITHDRAWING`, `POLLING_WITHDRAWAL` |
| Any, with `autoReconnect` | `RECONNECTING` |

Aborting before anything is sent rejects with the signal's reason. A request already sent is never abandoned or repeated:

* `deposit()` still resolves with the result once the transfer has started.
* A fill or withdrawal that may exist ends in `OrderOutcomeUnknown` or `WithdrawalOutcomeUnknown`.

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

const buyWithCancel = (outcomeId: string) =>
  agg.buy({ outcomeId, amount: '5', signal: controller.signal })

// Later, for example when the user leaves the screen:
controller.abort()
```

The `poll` options take `intervalMs` and `timeoutMs`. While polling, a helper reads through up to 5 transient failures in a row: a 429, 502, 503 or 504, or no response. Each request gives up after 120 seconds without an answer.

## Handling errors

Most failures are one of three kinds:

* **`AggError`**: a request the SDK refused to send, or a helper outcome. Check it with `AggError.is(error, reason?)` and branch on `reason`. `details` holds the context of each reason, and `cause` holds the failure that stopped the helper.
* **A failed Portal API request**: an `HttpError` from the Portal API. `AggApiError.from(error)` reads its `status`, Portal's `id`, `message`, Agg's `code` and `fields`, and the `traceId` it was sent with. It also unwraps the `cause` of `OrderOutcomeUnknown` and `WithdrawalOutcomeUnknown`.
* **`AggNoResponseError`**: the Portal API sent no usable answer, or none within 120 seconds. The request may or may not have been processed. `AggApiError.from()` also accepts it, returning only its `traceId`, so check for it first.

Other errors pass through unchanged: the signal's abort reason, a `PortalIdempotencyError` for an `idempotencyKey` Portal can't accept, a `PortalCredentialError`, and failures to read the wallet address or sign the link challenge in `connect()`.

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

const describeAggFailure = (error: unknown): string => {
  if (AggError.is(error, AggErrorReason.AmbiguousDepositToken)) {
    const addresses = error.details.candidates.map((token) => token.address)
    return `Choose one of these token addresses: ${addresses.join(', ')}`
  }

  if (AggError.is(error)) {
    return `${error.reason}: ${error.message}`
  }

  // Before AggApiError.from(), which also accepts it.
  if (error instanceof AggNoResponseError) {
    return `No response (trace ${error.traceId}). The request may still have been processed.`
  }

  const apiError = AggApiError.from(error)
  if (apiError?.isLinkRequired) {
    return 'Link the wallet again with connect().'
  }
  if (apiError?.isAccountAbstractionUnsupported) {
    return 'Agg needs a Portal client without account abstraction.'
  }
  if (apiError?.status === 403) {
    // A trade refused for the user's location, or a withdrawal to an address
    // that isn't on your allowlist: which one depends on the call you made.
    return `Request refused (403, trace ${apiError.traceId}): ${apiError.message ?? ''}`
  }
  if (apiError) {
    return `Request failed (${apiError.status}, trace ${apiError.traceId})`
  }

  return 'Something went wrong.'
}
```

> [!WARNING]
>
> Use `AggError.is(error)`, not `instanceof`. `AggError` is identified by a brand that works across copies of `@portal-hq/core`, so `instanceof` can return `false` for a real `AggError`. Only `AggError` has `.is()`. Check `AggNoResponseError` with `instanceof`, as in the example above.

Every `AggError` reason:

| `reason` | What happened | What to do |
| - | - | - |
| `NoAddress` | No Portal EVM wallet address is available to link. | Create or recover the wallet first. |
| `MissingRpcUrl` | No `gatewayConfig` entry for the chain `connect` signs on or `deposit` sends on. Nothing was sent. | Add the chain to `gatewayConfig`, or use another chain. |
| `AddressMismatch` | The link challenge names another address. Nothing was signed. | Report it to Portal support with the details. |
| `EmptyIdentifier` | An ID that goes in the request path (`eventId`, `outcomeId`, `quoteId` or `withdrawalId`) was empty. Nothing was sent. An empty ID in a request body is sent, and the API rejects it. | Pass the ID. |
| `InvalidAmount` | An amount, price or size isn't positive, has too many decimals, or is a price of 1 or more. Nothing was sent. | Fix the value. |
| `UnsupportedDepositToken` | Agg doesn't take that token on that chain. Nothing was sent. | Choose a token from the deposit addresses' `supportedChains`. |
| `AmbiguousDepositToken` | The token names more than one token on that chain, or Agg lists one address with conflicting decimals. Nothing was sent. | Pass the address of one of `details.candidates`. If they all share one address, the token can't be deposited until Agg's listing is corrected. |
| `DepositAddressesTimeout` | The deposit addresses weren't ready in time. Nothing was sent. | Call `deposit()` again, or raise `addressPoll.timeoutMs`. |
| `DepositOutcomeUnknown` | The deposit may have been sent. | See [When the outcome of a deposit is unknown](#when-the-outcome-of-a-deposit-is-unknown). |
| `QuoteNotTradable` | The quote isn't `ok`, or a venue reported a warning. Nothing was traded. | Show `details.quote` and quote again. |
| `OrderFailed` | The fill ended in a final state other than `filled` or `partially_filled`. | Show `details.status.errorReason`. |
| `OrderOutcomeUnknown` | The fill may exist. | Follow it with `getOrder(quote.quoteId, { mode })`, using the trade's `mode`. Never call `buy` or `sell` again. See [When the outcome of a fill is unknown](#when-the-outcome-of-a-fill-is-unknown). |
| `WithdrawalNotViable` | The withdrawal preview isn't `quoted`. Nothing was sent. | Show `details.preview.unviableReason`. |
| `WithdrawalFailed` | The withdrawal ended `failed`. | Show `details.withdrawal.errorMessage`. |
| `WithdrawalOutcomeUnknown` | The withdrawal may exist. | See [When the outcome of a withdrawal is unknown](#when-the-outcome-of-a-withdrawal-is-unknown). |

Portal's own refusals carry an `id`, exposed as `AggErrorId`:

| `id` | What to do |
| - | - |
| `AGG_LINK_REQUIRED` | Run `connect()` again, or use `autoReconnect`. |
| `AGG_ACCOUNT_ABSTRACTION_UNSUPPORTED` | The client is account-abstracted. Everything except discovery and market data is unavailable, `isConnected()` included. |
| `AGG_SESSION_REFRESH_IN_PROGRESS` | Another request is renewing the user's Agg session. The SDK retries the call up to 3 times before returning this error; retry after a moment. |
| `INTEGRATION_RESPONSE_SCHEMA_DRIFT` | Agg changed a response shape. Treat it as an outage until Portal adapts. A request that changes state may still have been processed. |

Agg's own declines have no `id`: they keep Agg's status (400, 403, 404, 409, 422 or 429), a message starting `Agg rejected the request`, and Agg's `code` and `fields` when it sent them. A 403 on a trading route usually means the user's location is blocked. Portal also returns a 403 without an `id` for a withdrawal to an address that isn't on your allowlist.

> [!NOTE]
>
> Quote `traceId` from `AggApiError.from(error)` when you report a failure to Portal support.

## Low-level APIs

The helpers cover the common flows. Each Portal API route, except self-custody signature submission (`POST /orders/{quoteId}/signatures`), also has its own method, which resolves with `{ data }` and rejects with the errors described in [Handling errors](#handling-errors), with no reconnecting, polling or retrying apart from the session-refresh retry above. See the [endpoint reference](https://docs.portalhq.io/integrations/Trading/agg.md#endpoint-reference) for each route.

| Area | 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` |

```typescript theme={null}
const { data: balances } = await agg.getBalances({ sync: true })

for (const cash of balances.cash) {
  console.log(`${cash.tokenSymbol}: ${cash.totalRaw} (${cash.decimals} decimals)`)
}
```

> [!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).

## Best practices

1. **Store what recovery needs in durable storage before calling**: the `idempotencyKey` for `deposit()`, the `quoteId` and `mode` for `buy()` and `sell()`, and the `requestId` and parameters for `withdraw()`
2. **Never repeat a helper after an `OutcomeUnknown` error**: follow the existing deposit, fill or withdrawal instead
3. **Bound every follow-up loop** with a deadline, and retry only transient failures
4. **Pass token addresses, not symbols**, when your app already knows them
5. **Show the quote** before the user confirms a trade: Portal adds no trading guardrails
6. **Turn on `autoReconnect`** so an expired Agg session costs the user one signature, not a failed action

## Next Steps

* Set up the integration: [Agg by Snag](https://docs.portalhq.io/integrations/Trading/agg.md)
* Retry transfers safely with [idempotency keys](https://docs.portalhq.io/sdks/react-native/guide/idempotency-keys.md)
* Approve signing requests with [custom signature hooks](https://docs.portalhq.io/sdks/react-native/guide/add-custom-signature-hooks.md)


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