> ## 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 iOS SDK.

Portal's iOS 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 PortalSwift `8.2.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 return its result.
* **API methods**, one per Portal API route except self-custody signature submission (`POST /orders/{quoteId}/signatures`), return the response as an `AggResponse` whose `data` holds the result. The same methods are also on `portal.api.agg`. 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, except where a chain has none: Agg then keeps its own id, such as Hyperliquid's `1337` in `supportedChains`. Agg executes orders from the user's Agg balance: self-custody fills aren't available through the iOS SDK yet.

## 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/ios/guide/getting-started.md) and [Create a wallet](https://docs.portalhq.io/sdks/ios/guide/create-a-wallet.md))
* An `rpcConfig` 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. When you don't pass `withRpcConfig`, Portal's default `rpcConfig` covers 11 chains, Polygon and Base included. A `withRpcConfig` you pass replaces the default entirely (see [Initializing Portal](https://docs.portalhq.io/sdks/ios/guide/getting-started.md#initializing-portal)).
* 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:

```swift theme={null}
import PortalSwift

// Without withRpcConfig, Portal's default rpcConfig covers Polygon and Base.
let portal = try Portal("YOUR_CLIENT_API_KEY_OR_CLIENT_SESSION_TOKEN")
let agg = portal.predictionMarkets.agg
```

## Quick start

The shortest path from a new user to a first trade. Each step has its own section below.

```swift theme={null}
func firstTrade() async throws {
  // 1. Link the Portal wallet to the user's Agg account. The user signs once.
  _ = try await agg.connect()

  // 2. Fund the Agg balance with 25 USDC from the wallet on Base.
  let deposit = try await agg.deposit(params: AggDepositParams(
    chainId: "eip155:8453",
    token: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
    amount: "25"
  ))
  print("Deposit sent in \(deposit.txHash)")

  // 3. Find an open outcome.
  let events = try await agg.listEvents(params: AggListEventsParams(status: .open, sortBy: .volume24hr, sortDir: .desc, limit: 1)).data.data
  guard let outcome = events.first?.venueMarkets?
    .first(where: { $0.status == .open })?
    .venueMarketOutcomes.first else { return }

  // 4. Spend 5 USD on it: buy quotes, fills at once and waits for the fill.
  let trade = try await agg.buy(params: AggBuyParams(outcomeId: outcome.id, amount: "5", slippageBps: 100))
  print("\(trade.status.overallState) for quote \(trade.quote.quoteId)")
}
```

Agg credits a deposit once the transfer confirms, so check `getBalances(sync: true, mode: nil)` before the first trade. To try trading without real funds, pass `mode: .paper` to `buy` (see [Buying and selling](#buying-and-selling)).

> [!WARNING]
>
> This is the happy path only. `deposit` and `buy` can fail with the outcome unknown, and calling them again then can send or trade twice. Before you move real money, store what recovery needs (see [Keeping what recovery needs](#keeping-what-recovery-needs)) and handle `depositOutcomeUnknown` and `orderOutcomeUnknown`.

## 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.

```swift theme={null}
let page = try await agg.listEvents(params: AggListEventsParams(
  status: .open,
  sortBy: .volume24hr,
  sortDir: .desc,
  limit: 10
)).data

for event in page.data {
  for market in event.venueMarkets ?? [] {
    for outcome in market.venueMarketOutcomes {
      print("\(event.title) · \(market.question) · \(outcome.label): \(outcome.id)")
    }
  }
}

// Lists are paginated: pass nextCursor as cursor while hasMore is true.
if page.hasMore, let cursor = page.nextCursor {
  let next = try await agg.listEvents(params: AggListEventsParams(cursor: cursor)).data
  print("Loaded \(next.data.count) more events")
}
```

An open event can contain closed markets, so check the market's `status` too before you quote an outcome. Use `search(params: AggSearchParams(q:type:))` for free-text search, and `getEvent(eventId:)` for one event. For prices, read `getMidpoints(venueMarketIds:)`, `getOutcomeOrderbook(outcomeId:depth:)` and `getChartBars(params: AggChartParams(venueMarketOutcomeId:to:))`, whose `to` and `from` are Unix milliseconds. 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.

```swift theme={null}
let link = try await agg.connect()
print("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 `rpcConfig` entry (`AggError.missingRpcUrl`),
* the client has no EVM address (`AggError.noAddress`), or
* the challenge names an address other than the wallet's own (`AggError.addressMismatch`).

Unless the `Portal` instance was created with `autoApprove: true`, the link signature reaches your `Events.PortalSigningRequested` handler as a normal `personal_sign` request, and the `deposit` transfer as a normal transaction (see [Add custom signature hooks](https://docs.portalhq.io/sdks/ios/guide/add-custom-signature-hooks.md)).

### 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. A call refused for the link did nothing, so the retry can't trade or send twice.
* 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. Keep Polygon (`eip155:137`) in your `rpcConfig`. Otherwise `reconnectFailed` wraps `missingRpcUrl`: call `connect(chainId:)` with your chain then (connecting after every launch would cost the user a signature each time).
* Helpers refused together share one `connect`, so the user signs once.
* If linking again fails, for example because the user declined the signature, the helper stops with `AggError.reconnectFailed` instead of asking the user to sign again: run `connect()`, then call the helper again. The exception is `withdraw` after its `withdrawing` step, where an earlier attempt may have created the withdrawal: follow it instead (see [Withdrawing](#withdrawing)).

`autoReconnect` applies to helpers only. The [low-level APIs](#low-level-apis) throw `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 **before** the request that can create the operation:

| Operation | Store | To |
| - | - | - |
| `deposit` | `idempotencyKey`, `chainId`, the token's address, `amount` and when it started | Retry the same deposit with the same key |
| `buy`, `sell` | `quoteId`, from the `filling` progress event, `mode` and the quote's `expiresAt` | Follow the fill with `getOrder(quoteId:mode:)` |
| `placeLimitOrder` | Your `clientOrderId` | Find an order whose answer was lost |
| `withdraw` | `requestId`, the withdrawal parameters and when it started | Follow the withdrawal, or send `createWithdrawal` again with the same `requestId` |

The start time matters because the safety of a retry depends on age: don't retry a deposit older than 24 hours, or a withdrawal more than a few days old, automatically. Check the chain (for a deposit) or `getWithdrawal` and `listActivity` (for a withdrawal) first.

The examples in this guide use this protocol for that storage. Implement it with storage that has written the record when `save` returns, such as a file or the Keychain: `onProgress` can't wait for asynchronous work, and the `filling` event is reported just before the fill is sent. Choose a Keychain accessibility or file protection class that allows writes while your app runs, including when the device is locked. The examples never let a storage error replace the helper's own error or result.

```swift theme={null}
/// Durable storage your app owns. The SDK does not persist recovery data.
protocol PendingOperationStore {
  func save(_ key: String, _ value: [String: String]) throws
  func remove(_ key: String) throws
  /// The stored records whose keys start with `prefix`, to resume after a restart.
  func all(prefix: String) throws -> [String: [String: String]]
}
```

A record is saved before the helper runs, so after a crash it can't tell by itself whether anything was sent. The examples below save it again from `onProgress`: they mark a deposit or withdrawal record sent at `.sendingDeposit` or `.withdrawing`, add the transaction hash at `.depositSent` and the `withdrawalId` at `.pollingWithdrawal`, and save a trade's placeholder before calling `buy`, adding the `quoteId` at `filling`. On restart, drop deposit and withdrawal records never marked sent, and trade records without a `quoteId`: nothing was sent for them. If marking a record failed (the examples log it), treat it as unknown rather than drop it. Follow a withdrawal that has a `withdrawalId` with `getWithdrawal(withdrawalId:)` instead of sending it again.

Following an operation means reading 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 this helper:

```swift theme={null}
/// No answer, a rate limit or a gateway error: worth reading again.
func isTransientAggError(_ error: Error) -> Bool {
  if let status = AggApiError.from(error)?.status {
    return [429, 502, 503, 504].contains(status)
  }
  // A request that got no answer because of a network error, as the SDK's helpers count it.
  let networkErrors: Set<URLError.Code> = [.timedOut, .networkConnectionLost, .notConnectedToInternet, .cannotConnectToHost, .cannotFindHost, .dnsLookupFailed]
  guard let urlError = (error as? AggRequestError)?.underlyingError as? URLError else {
    return false
  }
  return networkErrors.contains(urlError.code)
}
```

## Funding the Agg balance

`deposit(params:)` sends a token from the Portal wallet to the user's Agg deposit address and returns 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):

```swift theme={null}
func fundAgg(store: PendingOperationStore) async throws {
  let idempotencyKey = generateIdempotencyKey()
  let storeKey = "agg-deposit:\(idempotencyKey)"
  let record = [
    "idempotencyKey": idempotencyKey,
    "chainId": "eip155:8453", // Base
    "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base: an address, retried as is
    "amount": "25",
    "createdAt": ISO8601DateFormatter().string(from: Date()),
  ]

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

  let params = AggDepositParams(
    chainId: record["chainId"]!,
    token: record["token"]!,
    amount: record["amount"]!,
    idempotencyKey: idempotencyKey,
    onProgress: { event in
      // Mark the record sent before the transfer can go out, and keep the hash once it has.
      var marked = record
      marked["sent"] = "true"
      if event.step == .depositSent, let txHash = event.txHash {
        marked["txHash"] = txHash
      }
      if event.step == .sendingDeposit || event.step == .depositSent {
        do { try store.save(storeKey, marked) } catch { print("Couldn't mark the deposit: \(error)") }
      }
    },
    autoReconnect: true
  )

  do {
    let result = try await portal.predictionMarkets.agg.deposit(params: params)
    // Broadcast: from here on, the transaction hash identifies the transfer.
    try? store.remove(storeKey)
    print("Sent \(result.token.symbol) in \(result.txHash)")
  } catch {
    if case AggError.depositOutcomeUnknown = error {
      // The transfer may have gone out: keep the record and retry with the same key.
    } else {
      // Nothing was sent: drop the record, so a later resume can't send under this unused key.
      try? store.remove(storeKey)
    }
    throw error
  }
}
```

When `deposit` fails with `AggError.depositOutcomeUnknown`, keep the stored record until you know the outcome. Any other error from a first attempt means nothing was sent: remove the record, and deposit again with new params, which get a new key.

`AggDepositParams` takes:

| Parameter | Type | Default | Description |
| - | - | - | - |
| `chainId` | `String` | | The CAIP-2 chain to send from. It must be one of the deposit addresses' `supportedChains`. |
| `token` | `String` | | 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` | | A positive decimal string, such as `"10"` or `"1.5"`. |
| `idempotencyKey` | `String` | A new key | The key the transfer is sent with. Generated when you create the params, and reported on the `sendingDeposit` event, in the result and in `depositOutcomeUnknown`. |
| `onProgress` | `AggProgressHandler?` | `nil` | See [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts). |
| `autoReconnect` | `Bool` | `false` | See [When the link expires](#when-the-link-expires). |
| `addressPoll` | `AggPollOptions` | `interval: 2`, `timeout: 60` | How to wait for the deposit addresses, in seconds. |

`deposit` returns an `AggDepositResult` with `txHash`, `depositAddress`, `chainId`, `token` (the token as Agg lists it on `chainId`) and `idempotencyKey`. Agg credits the deposit once the transfer confirms. To see it, read `getBalances(sync: true, mode: nil)`.

### 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 `AggError.unsupportedDepositToken`.
* When `token` names more than one, it fails with `AggError.ambiguousDepositToken`, whose `candidates` list 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 `AggError.depositOutcomeUnknown`: the transfer may or may not have been broadcast. It carries the `idempotencyKey`, `chainId`, `depositAddress`, `token`, `amount` and the `underlyingError`. A send that fails before anything could be broadcast, such as a declined signing approval or a transfer Portal refuses to build for insufficient funds, throws its own error instead.

1. **Check whether the transfer went out**, for example on the chain. A transfer missing from `listActivity(params: AggListActivityParams(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, it won't broadcast a second transfer under it. Retry with the token the first attempt resolved to, by its address.
3. **Read the retry's refusal from `underlyingError`.** Portal refuses a retry under a key it has already seen (sent, still in progress or failed) with an [idempotency rejection](https://docs.portalhq.io/sdks/ios/guide/idempotency-keys.md#handle-a-rejection), which arrives as the `underlyingError` of a new `depositOutcomeUnknown`.
4. **Remove the record once the outcome is settled**: after a successful retry, a `requestAlreadyCompleted` refusal (the first transfer went out), or a chain check that shows the first transfer landed, or that it didn't land and can no longer land (then deposit again with new params). Keep it after every other outcome, including `requestInProgress` and any other error from a retry, which means this retry sent nothing while the first attempt's outcome is still unknown.

```swift theme={null}
func retryDeposit(store: PendingOperationStore, storeKey: String, idempotencyKey: String, chainId: String, tokenAddress: String, amount: String, createdAt: Date) async throws {
  // Portal remembers a key for at least 24 hours; after that, a retry could send the deposit again.
  guard Date().timeIntervalSince(createdAt) < 24 * 60 * 60 else {
    throw MyAppError.checkTheChainFirst(storeKey: storeKey) // your app's own error type
  }
  do {
    _ = try await portal.predictionMarkets.agg.deposit(params: AggDepositParams(
      chainId: chainId,
      token: tokenAddress,
      amount: amount,
      idempotencyKey: idempotencyKey
    ))
    try? store.remove(storeKey) // sent
  } catch let AggError.depositOutcomeUnknown(_, _, _, _, _, underlyingError) {
    switch (underlyingError as? PortalMpcError)?.id {
    case PortalIdempotencyErrorId.requestInProgress:
      print("Still processing. Retry later with the same key.")
    case PortalIdempotencyErrorId.requestAlreadyCompleted:
      print("Already broadcast. Don't send it again.")
      try? store.remove(storeKey) // the first transfer went out
    case let id?:
      print("Unconfirmed (\(id)). Check the chain before sending under a new key.")
    case nil:
      print("Unconfirmed. Retry with the same key once the cause is fixed.")
    }
  } catch {
    // This retry sent nothing, but the first attempt's outcome is still unknown:
    // keep the stored record and retry later with the same key.
    throw error
  }
}
```

> [!WARNING]
>
> `deposit` builds the transfer again on every call, so Portal can refuse a retry with `IDEMPOTENCY_KEY_REUSED` when the rebuilt transfer differs, for example when Agg has issued a new deposit address. On Solana, each build carries a new recent blockhash, so a retry with the same key is normally refused with `IDEMPOTENCY_KEY_REUSED`, whatever happened to the first attempt. Before you send under a new key, wait until the first transfer is confirmed or can no longer land (on an EVM chain, the account nonce has moved past it; on Solana, its recent blockhash has expired), then check the chain, and use a new key only if it didn't land, as described in [Retry `sendAsset`](./idempotency-keys#retry-sendasset). For a deposit older than 24 hours, check the chain before retrying with any key.

> [!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(params:)` and `sell(params:)` quote an outcome, fill the quote at once, and wait for the fill to finish. They return an `AggTradeResult` with `quote`, `fill` and `status`, the final read of the fill. `status.overallState` is `.filled` or `.partiallyFilled`, and `status.orders` says how much filled. The fill is never sent again after a failure that may have reached Agg, not even a transient one.

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

```swift theme={null}
func buyOutcome(store: PendingOperationStore, outcomeId: String, mode: AggMode = .live) async throws {
  let storeKey = "agg-fill:\(UUID().uuidString)"
  let placeholder = ["outcomeId": outcomeId, "mode": mode.rawValue, "createdAt": ISO8601DateFormatter().string(from: Date())]
  // A placeholder before anything is sent: if it can't be stored, don't trade.
  try store.save(storeKey, placeholder)

  var sentQuote: AggQuote?
  let record: (AggQuote) -> [String: String] = { quote in
    placeholder.merging(["quoteId": quote.quoteId, "expiresAt": quote.expiresAt]) { $1 }
  }
  do {
    let result = try await portal.predictionMarkets.agg.buy(params: AggBuyParams(
      outcomeId: outcomeId,
      amount: "5", // USD to spend
      slippageBps: 100,
      mode: mode,
      onProgress: { event in
        if event.step == .filling, let quote = event.quote {
          // The fill is about to be sent: keep what following it would need.
          sentQuote = quote
          do {
            try store.save(storeKey, record(quote))
          } catch {
            print("Couldn't store quote \(quote.quoteId): \(error)") // saved again below if the fill fails
          }
        }
        // Each execution step carries a label that is ready to show.
        event.order?.steps.forEach { print($0.label) }
      },
      autoReconnect: true
    ))

    // The fill reached a final state, so there is nothing left to follow.
    try? store.remove(storeKey)
    print("\(result.status.overallState) for quote \(result.quote.quoteId)")
  } catch {
    var mayExist: AggQuote?
    if case let AggError.orderOutcomeUnknown(quote, _, _, _) = error {
      mayExist = quote
    } else if error is CancellationError || (error as? URLError)?.code == .cancelled {
      mayExist = sentQuote
    }
    if let quote = mayExist {
      // The fill may exist: keep the record (saving it again in case the save above failed) and follow it.
      do { try store.save(storeKey, record(quote)) } catch { print("Couldn't store the quote: \(error)") }
    } else {
      // Any other error means the fill finished without trading, or was never sent.
      try? store.remove(storeKey)
    }
    throw error
  }
}

// A minimal example: before you use it in production, store and follow the fill as buyOutcome does.
func sellOutcome(outcomeId: String) async throws {
  let result = try await portal.predictionMarkets.agg.sell(params: AggSellParams(outcomeId: outcomeId, shares: "3"))
  print(result.status.overallState)
}
```

The `filling` save happens before the fill is sent, so it covers a crash or a cancellation; `orderOutcomeUnknown` also carries the quote, so the example saves it again there.

`AggBuyParams` and `AggSellParams` take:

| Parameter | Type | Description |
| - | - | - |
| `outcomeId` | `String` | `venueMarketOutcomes[].id` of a market. |
| `amount` | `String` | `buy` only. The USD to spend, as a decimal string. Venue minimums are usually counted in shares, so very small amounts quote as `min_order_size_violated`. |
| `shares` | `String` | `sell` only. The shares to sell, as a decimal string. |
| `slippageBps` | `Int?` | The slippage tolerance, in basis points. |
| `venues` | `[AggVenue]?` | Restrict routing to these venues, for example `[.polymarket]`. |
| `mode` | `AggMode?` | `.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` | `interval` 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 0.25 and 10 seconds. `timeout` always applies (default 180 seconds). |

Both also take `onProgress` and `autoReconnect` (see [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts)). They fail with:

* **`AggError.quoteNotTradable`**: the quote's `status` isn't `ok`, a venue reported a warning, or Agg attached an `error`. Nothing was traded. The error carries the `quote`, with its `status`, `error` and `warnings`.
* **`AggError.orderFailed`**: the fill ended in a final state other than filled or partially filled. The error carries the final read as `status`, with `errorReason`.
* **`AggError.orderOutcomeUnknown`**: the fill may exist, but the helper couldn't see it finish, for example after a timeout, a lost connection or a 5xx on the fill request.
* **The request's error, unchanged**: 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 `AggError.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. The error carries the `quote`, the `fill` when it was placed, and `last`, the last read of the fill.

This example uses `PendingOperationStore` and `isTransientAggError` from [Keeping what recovery needs](#keeping-what-recovery-needs). `MyAppError` stands for your app's own error type:

```swift theme={null}
/// Reads a fill until it is final, retrying transient failures, for up to `timeout` seconds.
func followFill(quoteId: String, mode: AggMode, timeout: TimeInterval = 600) async throws -> AggExecutionStatus {
  let deadline = Date().addingTimeInterval(timeout)
  var wait: TimeInterval = 1

  while Date() < deadline {
    do {
      let status = try await portal.predictionMarkets.agg.getOrder(quoteId: quoteId, mode: mode).data
      if status.terminal {
        return status
      }
      wait = min(max(Double(status.pollAfterMs ?? 1000) / 1000, 0.25), 10) // as the SDK does
    } catch where isTransientAggError(error) {
      wait = min(wait * 2, 30)
    }
    try await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
  }

  // Keep the stored quoteId and mode, and check again later. Any other error thrown above keeps the
  // record too; after AGG_LINK_REQUIRED (these routes don't reconnect), run connect() and follow again.
  throw MyAppError.fillNotFinalYet(quoteId: quoteId)
}

func buyOnce(store: PendingOperationStore, outcomeId: String, amount: String, mode: AggMode) async throws -> AggExecutionStatus {
  do {
    return try await portal.predictionMarkets.agg.buy(params: AggBuyParams(outcomeId: outcomeId, amount: amount, mode: mode)).status
  } catch let AggError.orderOutcomeUnknown(quote, _, _, _) {
    // Follow the existing fill instead of trading again.
    let storeKey = "agg-fill:\(quote.quoteId)"
    do { try store.save(storeKey, ["quoteId": quote.quoteId, "mode": mode.rawValue, "expiresAt": quote.expiresAt]) } catch { print("Couldn't store the quote: \(error)") }

    let status = try await followFill(quoteId: quote.quoteId, mode: mode)
    try? store.remove(storeKey)
    // Final, but not necessarily traded: check status.overallState for .filled or .partiallyFilled.
    return status
  }
}
```

`buyOnce` saves the quote only from the error: combine it with the `filling` save from `buyOutcome` so a crash or a cancellation also leaves a record. After a restart, or after the task was cancelled (see [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts)), call `followFill` with each stored `quoteId` and `mode`. A record saved at `filling` or on a cancellation may belong to a fill that was never sent: once the quote's `expiresAt` has passed and `listOrders(params: AggListOrdersParams(quoteId:mode:))` shows no order for it, drop the record.

When the error's `fill` is `nil`, 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(params: AggListOrdersParams(quoteId:mode:))` and the user's activity before you trade again.

## Limit orders

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

```swift theme={null}
func placeAndCancel(venueMarketOutcomeId: String) async throws {
  let agg = portal.predictionMarkets.agg
  let order = try await agg.placeLimitOrder(params: AggPlaceLimitOrderParams(
    venue: .polymarket,
    venueMarketOutcomeId: venueMarketOutcomeId,
    side: .buy,
    price: "0.42", // USD per share
    shares: "10"
  ))
  print("Order \(order.orderId) is \(order.status)")

  let cancelled = try await agg.cancelOrder(request: AggCancelOrderRequest(orderId: order.orderId)).data
  print("Cancel \(cancelled.status)")
}
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `venue` | `AggVenue` | | The venue of the market. |
| `venueMarketOutcomeId` | `String` | | `venueMarketOutcomes[].id` of a market on that venue. |
| `side` | `AggSide` | | `.buy` or `.sell`. |
| `price` | `String` | | USD per share, greater than 0 and less than 1, with at most 6 decimals, for example `"0.2"`. |
| `shares` | `String` | | Shares, with at most 6 decimals. |
| `timeInForce` | `AggTimeInForce` | `.gtc` | `.gtc`, `.gtd`, `.fok`, `.fak`, `.ioc` or `.alo`. |
| `postOnly` | `Bool?` | `nil` | Place the order only if it rests on the book instead of trading at once. |
| `expiresAt` | `String?` | `nil` | When the order expires. Required with `.gtd`. |
| `clientOrderId` | `String?` | `nil` | Your own ID for the order, returned on `listOrders`. |

It also takes `onProgress` and `autoReconnect`. Before sending, the SDK checks only that `price` and `shares` are positive decimal strings with at most 6 decimals, and that `price` is greater than 0 and less than 1. Anything else fails with `AggError.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` returns, 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. When the error is an `AggRequestError` and `AggApiError.from(_:)` is `nil` (no answer, or a response that didn't decode), or the status is a 5xx other than `AGG_SESSION_REFRESH_IN_PROGRESS`, the order may have been placed: check `listOrders(params: AggListOrdersParams(orderType: .limit))` before placing it again. Pass a `clientOrderId`, stored before you call, so you can find the order there even after a crash.

## Redeeming winnings

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

```swift theme={null}
let batches = try await portal.predictionMarkets.agg.redeemAll(params: AggRedeemAllParams(autoReconnect: true))

for batch in batches {
  for result in batch.results {
    print("\(result.venueMarketOutcomeId): \(result.status)")
  }
}
```

If a batch fails, the batches before it are already redeemed, and their results are not returned. Calling `redeemAll` again redeems only what is still eligible; check `listPositions` and `listActivity(params: AggListActivityParams(type: .redeem))` first.

To redeem specific positions, call `redeemPositions(request: AggRedeemRequest(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(params:)` 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 returns the withdrawal once its `status` is `.completed` or `.partial`.

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

```swift theme={null}
func withdrawToBase(store: PendingOperationStore) async throws {
  var reachedWithdrawing = false
  let requestId = UUID().uuidString.lowercased()
  let storeKey = "agg-withdrawal:\(requestId)"
  let record = [
    "requestId": requestId,
    "amount": "10", // no more decimals than the token has, so the stored amount is the one sent
    "tokenSymbol": AggTokenSymbol.usdc.rawValue,
    "destinationChainId": "eip155:8453",
    "createdAt": ISO8601DateFormatter().string(from: Date()),
    // Also store destinationAddress when you pass one: resuming needs it.
  ]

  // Persist before calling, so a withdrawal that may exist can be followed
  // after withdrawalOutcomeUnknown, a cancellation, a crash or a restart.
  try store.save(storeKey, record)

  let params = AggWithdrawParams(
    amount: record["amount"]!,
    tokenSymbol: .usdc,
    destinationChainId: record["destinationChainId"]!,
    requestId: requestId,
    onProgress: { event in
      // Mark the record sent before the withdrawal is created, and keep its id once known.
      var marked = record
      marked["sent"] = "true"
      if event.step == .withdrawing {
        reachedWithdrawing = true
        do { try store.save(storeKey, marked) } catch { print("Couldn't mark the withdrawal: \(error)") }
      }
      if event.step == .pollingWithdrawal, let withdrawal = event.withdrawal {
        marked["withdrawalId"] = withdrawal.withdrawalId
        do { try store.save(storeKey, marked) } catch { print("Couldn't store the withdrawal id: \(error)") }
      }
    },
    autoReconnect: true
  )

  do {
    let withdrawal = try await portal.predictionMarkets.agg.withdraw(params: params)
    try? store.remove(storeKey)
    print("Withdrawal \(withdrawal.withdrawalId) is \(withdrawal.status)")
  } catch {
    // Before the withdrawing step nothing was sent, and withdrawalFailed is final: drop the record.
    // Any other error after the withdrawing step may hide a withdrawal: keep it and follow it.
    if !reachedWithdrawing {
      try? store.remove(storeKey)
    } else if case AggError.withdrawalFailed = error {
      try? store.remove(storeKey)
    }
    throw error
  }
}
```

`AggWithdrawParams` takes:

| Parameter | Type | Default | Description |
| - | - | - | - |
| `amount` | `String` | | A decimal string in `tokenSymbol`, rounded down to the token's decimals. |
| `tokenSymbol` | `AggTokenSymbol` | | The token to withdraw, for example `.usdc`. |
| `destinationChainId` | `String` | | The CAIP-2 chain to withdraw to. |
| `destinationAddress` | `String?` | `nil` | 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` | A new UUID | Agg uses it to avoid creating the withdrawal twice, and takes only a UUID. Generated once when you create the params: create new params for a new withdrawal. |
| `poll` | `AggPollOptions` | `interval: 5`, `timeout: 600` | How to read the withdrawal, in seconds. |

It also takes `onProgress` and `autoReconnect`. It fails with:

* **`AggError.withdrawalNotViable`**: the preview didn't price as `quoted`. Nothing was sent. The error carries the `preview`, with its `pricingStatus` and `unviableReason`.
* **`AggError.withdrawalFailed`**: the withdrawal ended `failed`. The error carries the `withdrawal`, with its `errorMessage`.
* **`AggError.withdrawalOutcomeUnknown`**: the withdrawal may exist. It is thrown when the last attempt to create it got no definite answer (no answer, a 5xx other than a session refresh, or a response that didn't decode), or when reading it failed or timed out after it was created. A cancellation is thrown as is.
* **The request's error, unchanged**: Portal or Agg refused the preview, or the withdrawal, with a definite answer, such as a 4xx. Before the `withdrawing` step, nothing was withdrawn. A refusal of the withdrawal itself may still follow an earlier attempt that created it: see the warning below. A 403 here usually means `destinationAddress` isn't on your allowlist.

When creating the withdrawal fails with a rate limit, a 502, 503 or 504, or a network error such as a timeout or a lost connection, `withdraw` sends the same request again, with the same `requestId`, up to 3 attempts in all.

> [!WARNING]
>
> Only the last attempt's error decides what `withdraw` throws. If an earlier attempt got no definite answer (a network error, or a 502, 503 or 504), the withdrawal may exist even when the last attempt was refused, for example with a 429, `AGG_SESSION_REFRESH_IN_PROGRESS`, `AGG_LINK_REQUIRED` or `AggError.reconnectFailed`, and that refusal is thrown as is. So treat any error from `withdraw` after the `withdrawing` progress step, other than `withdrawalFailed`, as a withdrawal that may exist: keep the stored `requestId` and follow it with `createWithdrawal(request:)` as below, and don't create new params until that is resolved.

### When the outcome of a withdrawal is unknown

After `AggError.withdrawalOutcomeUnknown`, **never call `withdraw` again**. With new params it would create a second withdrawal, and with the same ones it would preview again, and the preview can refuse funds that are already on their way. Follow the existing withdrawal instead:

* When the error carries a `withdrawal`, it was created: read `getWithdrawal(withdrawalId:)`.
* When `withdrawal` is `nil`, creating it got no definite answer: send `createWithdrawal(request:)` again with the error's `request`, then read it. The request carries the same `requestId`, so Agg returns the original withdrawal instead of creating a second one.

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

```swift theme={null}
/// Follows a withdrawal that may exist until it is final, for up to `timeout` seconds.
func followWithdrawal(request: AggWithdrawalRequest, withdrawal: AggWithdrawal?, timeout: TimeInterval = 1800) async throws -> AggWithdrawal {
  let agg = portal.predictionMarkets.agg
  let finalStatuses: [AggWithdrawalStatus] = [.completed, .partial, .failed]
  let deadline = Date().addingTimeInterval(timeout)
  var withdrawalId = withdrawal?.withdrawalId
  var wait: TimeInterval = 5

  while Date() < deadline {
    do {
      // Same requestId: Agg returns the original withdrawal instead of creating another.
      let id: String
      if let withdrawalId {
        id = withdrawalId
      } else {
        id = try await agg.createWithdrawal(request: request).data.withdrawalId
        withdrawalId = id
      }

      let latest = try await agg.getWithdrawal(withdrawalId: id).data
      if finalStatuses.contains(latest.status) {
        return latest
      }
      wait = 5
    } catch where isTransientAggError(error) {
      wait = min(wait * 2, 60)
    }
    try await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
  }

  // Keep the stored request, and check again later. Any other error thrown above keeps the
  // record too; after AGG_LINK_REQUIRED (these routes don't reconnect), run connect() and follow again.
  throw MyAppError.withdrawalNotFinalYet(requestId: request.requestId ?? "")
}

// After withdraw(params:) fails:
// catch let AggError.withdrawalOutcomeUnknown(request, withdrawal, _, _) {
//   let final = try await followWithdrawal(request: request, withdrawal: withdrawal)
//   try? store.remove(storeKey) // final: nothing left to follow
// }
```

An error before the `withdrawing` step means nothing was sent: remove the record. To resume after your app restarts, or after the task was cancelled or failed with any error other than `withdrawalFailed` once `withdraw` had reached the `withdrawing` step:

1. Build an `AggWithdrawalRequest` from what you stored: the same `requestId`, `tokenSymbol`, `destinationChainId` and `destinationAddress`. A request with changed parameters is refused, and a `requestId` can't be combined with `max`.
2. Pass the amount in base units as `amountRaw`, exactly as the first request sent it. `withdraw` rounds the amount down to the token's decimals, so pass an amount with no more decimals than the token has: `amountRaw` is then the amount times 10 to the power of the token's decimals, which `quoteWithdrawable(request: AggWithdrawableQuoteRequest(tokenSymbol:destinationChainId:))` returns as `decimals`. Or compute `amountRaw` up front and store it. When you have the `withdrawalOutcomeUnknown` error, its `request.amountRaw` is the exact value.
3. Call `followWithdrawal(request:withdrawal:)` with it and `nil`, and remove the record once it returns a final status.

If the stored request is refused with a definite answer (not a 429, 409, `AGG_LINK_REQUIRED` or a session refresh) and `listActivity(params: AggListActivityParams(type: .withdrawal))` shows no matching withdrawal, drop the record. Show the user a pending withdrawal, not a failed one, while a record exists. A `409` means Agg already holds a withdrawal under this `requestId` with different parameters, usually a wrongly computed `amountRaw`: find it in `listActivity(params: AggListActivityParams(type: .withdrawal))`, follow it with `getWithdrawal(withdrawalId:)`, and remove the record once it is final.

> [!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(withdrawalId:)` or `listActivity(params: AggListActivityParams(type: .withdrawal))` before sending a stored request that is days old.

## Progress, cancellation and timeouts

Every helper except `connect` and `isConnected` takes these parameters:

| Parameter | Type | Description |
| - | - | - |
| `onProgress` | `AggProgressHandler?` | Called at each step, on any thread. Switch to the main actor before you update your UI. |
| `autoReconnect` | `Bool` | On `AGG_LINK_REQUIRED`, link again and retry the refused call once. See [When the link expires](#when-the-link-expires). |

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

| Helper | Steps |
| - | - |
| `deposit` | `.awaitingDepositAddresses`, `.sendingDeposit` (with `idempotencyKey`), `.depositSent` (with `txHash`) |
| `buy`, `sell` | `.quoting`, `.filling` (with `quote`), `.pollingOrder` (with `fill`, then `order`) |
| `placeLimitOrder` | `.placingOrder` |
| `redeemAll` | `.redeeming`, once per batch |
| `withdraw` | `.previewingWithdrawal`, `.withdrawing` (with `withdrawalPreview`), `.pollingWithdrawal` (with `withdrawal`) |
| Any, with `autoReconnect` | `.reconnecting` |

To stop a helper, cancel the task that runs it. It throws `CancellationError`, or a `URLError` with code `.cancelled` when the cancellation interrupted a request in flight: check for both. A request already sent is never undone or repeated:

* `deposit` finishes a send it has started, and returns its result even when the task was cancelled.
* A `buy`, `sell` or `withdraw` cancelled after the fill or withdrawal was sent throws one of those two errors, but the fill or withdrawal may exist. Follow it from what you stored: the `quoteId` from the `filling` event with `followFill`, or the withdrawal's `requestId` with `createWithdrawal`.
* A `placeLimitOrder` or `redeemAll` cancelled mid-request can leave the order or the redemption in place: check `listOrders` or `listPositions`.

```swift theme={null}
// buyOutcome stores the quote at the filling step, so a cancelled fill can be followed.
let buyTask = Task {
  try await buyOutcome(store: store, outcomeId: outcomeId)
}

// Later, for example when the user leaves the screen:
buyTask.cancel()
```

`AggPollOptions` takes an `interval` and a `timeout`, in seconds. While polling, a helper reads through up to 5 transient failures in a row: a 429, 502, 503 or 504, or a request that got no answer because of a network error, such as a timeout or a lost connection. Any other failure, such as a 500, a 4xx, a TLS failure or a response that didn't decode, ends the wait. A wait that runs out fails with `AggError.depositAddressesTimeout` (nothing was sent, so `deposit` can be called again), or ends in `orderOutcomeUnknown` or `withdrawalOutcomeUnknown` carrying `AggError.orderTimeout` or `AggError.withdrawalTimeout` as its `underlyingError`.

## Handling errors

Most failures are one of three kinds:

* **`AggError`**: a request the SDK refused to send, or a helper outcome. Switch over its cases; each carries the context of that case.
* **A failed Portal API request**: an `AggRequestError`, which wraps the transport's error (a `PortalRequestsError`, a `URLError` or a `DecodingError`) as `underlyingError` with the request's `traceId`. The other Portal APIs throw the transport's error itself, so match `PortalRequestsError` on `underlyingError`. `AggApiError.from(_:)` reads the HTTP `status`, Portal's `id`, the `message`, Agg's `details` (`code` and `fields`) and the `traceId`. It returns `nil` when there was no HTTP answer, for example a lost connection, or when the response didn't decode.
* **Errors passed through unchanged**: `CancellationError` or a `URLError` with code `.cancelled` (see [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts)), a `PortalIdempotencyError` for an `idempotencyKey` Portal can't accept, a `PortalCredentialError`, a failure to sign the link challenge in `connect`, and a deposit send that failed before anything could be broadcast, such as a declined approval, a `PortalMpcError` like `INSUFFICIENT_FUNDS`, or a failed request to build the transfer. These carry no trace id.

```swift theme={null}
func describeAggFailure(_ error: Error) -> String {
  if error is CancellationError || (error as? URLError)?.code == .cancelled {
    return "Cancelled. A fill or withdrawal that was already sent may still exist: follow it."
  }
  if case let AggError.ambiguousDepositToken(_, _, candidates) = error {
    return "Choose one of these token addresses: \(candidates.map(\.address).joined(separator: ", "))"
  }
  if let aggError = error as? AggError {
    return aggError.localizedDescription
  }

  if let 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 ?? "none")): \(apiError.message ?? "")"
    }
    return "Request failed (\(apiError.status.map(String.init) ?? "no status"), trace \(apiError.traceId ?? "none"))"
  }

  if let requestError = error as? AggRequestError {
    return "No usable answer (trace \(requestError.traceId)). The request may still have been processed."
  }
  return "Something went wrong."
}
```

Every `AggError` case:

| Case | What happened | What to do |
| - | - | - |
| `noAddress` | No Portal EVM wallet address is available to link. | Create or recover the wallet first. |
| `missingRpcUrl` | No `rpcConfig` entry for the chain `connect` signs on or `deposit` sends on. Nothing was signed or sent. | Add the chain to `rpcConfig`, 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. | Pass the ID. |
| `invalidAmount` | An amount, price or size isn't positive, has too many decimals, or is a limit price that isn't greater than 0 and less than 1. Nothing was sent. | Fix the value. |
| `missingDependency` | A standalone `Agg` was built without something `Portal` provides. | Use `portal.predictionMarkets.agg`, or pass the dependency. |
| `reconnectFailed` | A call was refused for the link, and the `connect` that `autoReconnect` ran failed. The refused call did nothing. | Run `connect()` (with your chain, when Polygon isn't in `rpcConfig`), then call the helper again, except `withdraw` after its `withdrawing` step: follow the withdrawal and never create new params. |
| `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 the `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 the `addressPoll` timeout. |
| `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`, a venue reported a warning, or Agg attached an `error`. Nothing was traded. | Show the quote's warnings or error, and quote again. |
| `orderFailed` | The fill ended in a final state other than filled or partially filled. | Show the status's `errorReason`. |
| `orderTimeout` | A wait for a fill ran out; the fill may still finish. It reaches you as the `underlyingError` of `orderOutcomeUnknown`. | Follow the fill. |
| `orderOutcomeUnknown` | The fill may exist. | Follow it with `getOrder(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 the preview's `unviableReason`. |
| `withdrawalFailed` | The withdrawal ended `failed`. | Show the withdrawal's `errorMessage`. |
| `withdrawalTimeout` | A wait for a withdrawal ran out; it may still finish. It reaches you as the `underlyingError` of `withdrawalOutcomeUnknown`. | Follow the withdrawal. |
| `withdrawalOutcomeUnknown` | The withdrawal may exist. | See [When the outcome of a withdrawal is unknown](#when-the-outcome-of-a-withdrawal-is-unknown). |

Portal's typed refusals carry an `id`, available as a constant on `AggErrorId` and as a property on `AggApiError`. Its validation failures (a `400` such as `Invalid request body…`) and the allowlist `403` have no `id`.

| `id` | Constant / property | What to do |
| - | - | - |
| `AGG_LINK_REQUIRED` | `linkRequired` / `isLinkRequired` | Run `connect()` again, or use `autoReconnect`. From `withdraw` after its `withdrawing` step, follow the withdrawal instead of calling it again with new params. |
| `AGG_ACCOUNT_ABSTRACTION_UNSUPPORTED` | `accountAbstractionUnsupported` / `isAccountAbstractionUnsupported` | The client is account-abstracted. Everything except discovery and market data is unavailable, `isConnected()` included. |
| `AGG_SESSION_REFRESH_IN_PROGRESS` | `sessionRefreshInProgress` / `isSessionRefreshInProgress` | Another request is renewing the user's Agg session. The SDK retries the call after 0.5, 1 and 2 seconds before returning this error, except for limit orders, cancels, redemptions and withdrawals without a `requestId`, which return it at once. Retry after a moment, except `withdraw` after its `withdrawing` step: follow the withdrawal. |
| `INTEGRATION_RESPONSE_SCHEMA_DRIFT` | `integrationResponseSchemaDrift` / `isSchemaDrift` | 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` in `details` 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 the `traceId` from `AggApiError.from(_:)`, or from the `AggRequestError`, when you report a failure to Portal support.

To follow fills and withdrawals from your backend as well, see [Webhooks](https://docs.portalhq.io/integrations/Trading/agg.md#webhooks) on the integration page.

## Values Agg may add

Statuses, venues and token symbols, such as `AggMarketStatus`, `AggVenue`, `AggTokenSymbol`, `AggExecutionState` and `AggWithdrawalStatus`, are open values (`AggOpenValue`): a struct with a `rawValue` and a static constant for each known value, such as `AggVenue.polymarket`. A value Agg adds later still decodes, with its `rawValue`, instead of failing the response. Compare against the known constants, and add a fallback for the rest. Request options such as `AggMode`, `AggSide`, `AggTimeInForce` and the sort and type filters are closed Swift enums.

## 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 returns the response in an `AggResponse` and throws the `AggRequestError` as is, 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.

Be careful when you repeat a state-changing call after a failure with no definite answer: never send `createOrder` for the same quote again; `createDirectOrder` refuses a repeated `externalId` with a `409`; list orders with `orderType: .limit` and look for your `clientOrderId` before you repeat `createLimitOrder`; and `createWithdrawal` is only safe to repeat with the same `requestId`.

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

```swift theme={null}
let balances = try await portal.predictionMarkets.agg.getBalances(sync: true, mode: nil).data

for cash in balances.cash {
  print("\(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).

## Testing

`portal.predictionMarkets` is a `PredictionMarkets`, and `PortalProtocol` exposes it. To use your own implementation in a `PortalProtocol` test double, build the namespace around an `AggProtocol` conformance with `PredictionMarkets(agg:)`. `PortalApiProtocol` also exposes the route methods as `agg`.

## Best practices

1. **Store what recovery needs in durable storage before the request**: the `idempotencyKey` for `deposit`, the `quoteId` (from the `filling` event) and `mode` for `buy` and `sell`, and the `requestId` and parameters for `withdraw`
2. **Never repeat `buy`, `sell` or `withdraw` after an outcome-unknown error or a cancellation**, nor `withdraw` after any error once it reached its `withdrawing` step: follow the existing fill or withdrawal instead, and retry `deposit` only with the same `idempotencyKey`
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. **Preview the price** before the user confirms a trade, for example with `createQuote`, and pass `slippageBps` to `buy` and `sell`, which fill at once: Portal adds no trading guardrails
6. **Check a quote before you offer it**: a quote prices every venue, including ones this user can't trade on, so `status == .ok` only means pricing succeeded. Offer it only when `quote.status == .ok`, `(quote.warnings ?? []).isEmpty` and `(quote.error ?? "").isEmpty`; otherwise show each warning's `reason` as is. `buy` and `sell` run the same check and throw `quoteNotTradable` (see [Trading](https://docs.portalhq.io/integrations/Trading/agg.md#trading) on the integration page)
7. **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/ios/guide/idempotency-keys.md)
* Approve signing requests with [custom signature hooks](https://docs.portalhq.io/sdks/ios/guide/add-custom-signature-hooks.md)


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