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

Portal's Android 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.

`portal.predictionMarkets` requires Portal Android SDK `11.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 return its result.
* **API methods**, one per Portal API route except self-custody signature submission (`POST /orders/{quoteId}/signatures`), return the response, whose `data` holds the result. The same methods are also on `portal.api.agg`. See [Low-level APIs](#low-level-apis).

Every method is a `suspend` function that returns a Kotlin `Result`: read it with `getOrThrow()`, `getOrElse`, `onSuccess` / `onFailure` or `fold`. 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 Android 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/android/guide/getting-started.md) and [Create a wallet](https://docs.portalhq.io/sdks/android/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 `rpcConfig`, Portal's default `rpcConfig` covers 11 chains, Polygon and Base included. An `rpcConfig` you pass replaces the default entirely (see [Initializing Portal](https://docs.portalhq.io/sdks/android/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 returns a failed `Result` instead of `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:

```kotlin theme={null}
import io.portalhq.android.Portal

// Without rpcConfig, Portal's default rpcConfig covers Polygon and Base.
val portal = Portal(apiKey = CLIENT_API_KEY)
val 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.

```kotlin theme={null}
import io.portalhq.android.api.data.agg.AggEventSort
import io.portalhq.android.api.data.agg.AggListEventsParams
import io.portalhq.android.api.data.agg.AggMarketStatus
import io.portalhq.android.api.data.agg.AggSortDirection

val page = agg.listEvents(
    AggListEventsParams(
        status = AggMarketStatus.OPEN,
        sortBy = AggEventSort.VOLUME_24HR,
        sortDir = AggSortDirection.DESC,
        limit = 10,
    ),
).getOrThrow().data

for (event in page.data) {
    for (market in event.venueMarkets.orEmpty()) {
        for (outcome in market.venueMarketOutcomes) {
            println("${event.title} · ${market.question} · ${outcome.label}: ${outcome.id}")
        }
    }
}

// Lists are paginated: pass nextCursor as cursor while hasMore is true.
val cursor = page.nextCursor
if (page.hasMore && cursor != null) {
    val next = agg.listEvents(AggListEventsParams(cursor = cursor)).getOrThrow().data
    println("Loaded ${next.data.size} more events")
}
```

An open event can contain closed markets, so check the market's `status` too before you quote an outcome. Use `search(AggSearchParams(q = …, type = AggSearchType.EVENTS))` for free-text search, and `getEvent(eventId)` for one event. For prices, read `getMidpoints(venueMarketIds)`, `getOutcomeOrderbook(outcomeId, depth)` and `getChartBars(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.

```kotlin theme={null}
val link = agg.connect().getOrThrow()
println("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 (`AggException.MissingRpcUrl`),
* the client has no EVM address (`AggException.NoAddress`), or
* the challenge names an address other than the wallet's own (`AggException.AddressMismatch`).

Unless the `Portal` instance was created with `autoApprove = true`, the link signature reaches your `portal_signingRequested` 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/android/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, as a `Result<Boolean>`, 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 the reconnect fails with `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 and returns that failure, as `connect` reported it, 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) fail 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 **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 interface for that storage. `onProgress` is a plain function that can't suspend, and the `FILLING` event is reported just before the fill is sent, so implement `save` with storage that has written the record when it returns, such as `SharedPreferences` with `commit()` or a file. The examples never let a storage error replace the helper's own error or result.

```kotlin theme={null}
/** Durable storage your app owns. The SDK does not persist recovery data. */
interface PendingOperationStore {
    /** Returns once the record is written. */
    fun save(key: String, value: Map<String, String>)
    fun remove(key: String)
    /** The stored records whose keys start with [prefix], to resume after a restart. */
    fun all(prefix: String): Map<String, Map<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 `SENDING_DEPOSIT` or `WITHDRAWING`, add the transaction hash at `DEPOSIT_SENT` and the `withdrawalId` at `POLLING_WITHDRAWAL`, 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:

```kotlin theme={null}
import io.portalhq.android.predictionmarkets.AggApiError
import java.io.IOException

/** No answer, a rate limit or a gateway error: worth reading again. */
fun isTransientAggError(error: Throwable): Boolean {
    // A request that got no answer, such as a timeout or a lost connection.
    if (error is IOException) return true
    return AggApiError.from(error)?.status in setOf(429, 502, 503, 504)
}
```

## 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):

```kotlin theme={null}
import io.portalhq.android.predictionmarkets.AggDepositParams
import io.portalhq.android.predictionmarkets.AggHelperStep
import io.portalhq.android.utils.generateIdempotencyKey
import java.time.Instant

suspend fun fundAgg(store: PendingOperationStore) {
    val idempotencyKey = generateIdempotencyKey()
    val storeKey = "agg-deposit:$idempotencyKey"
    val record = mapOf(
        "idempotencyKey" to idempotencyKey,
        "chainId" to "eip155:8453", // Base
        "token" to "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base: an address, retried as is
        "amount" to "25",
        "createdAt" to Instant.now().toString(),
    )

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

    var sending = false
    val params = AggDepositParams(
        chainId = record.getValue("chainId"),
        token = record.getValue("token"),
        amount = record.getValue("amount"),
        idempotencyKey = idempotencyKey,
        onProgress = { event ->
            // Mark the record sent before the transfer can go out, and keep the hash once it has.
            val marked = when (event.step) {
                AggHelperStep.SENDING_DEPOSIT -> record + ("sent" to "true")
                AggHelperStep.DEPOSIT_SENT -> record + mapOf("sent" to "true", "txHash" to event.txHash.orEmpty())
                else -> null
            }
            if (marked != null) {
                sending = true
                runCatching { store.save(storeKey, marked) }
                    .onFailure { println("Couldn't mark the deposit: $it") }
            }
        },
        autoReconnect = true,
    )

    val result = portal.predictionMarkets.agg.deposit(params).getOrElse { error ->
        if (!sending) {
            // Nothing was sent: drop the record, so a later resume can't send under this unused key.
            runCatching { store.remove(storeKey) }
        }
        // After SENDING_DEPOSIT the transfer may have gone out: keep the record and retry with the same key.
        throw error
    }

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

When `deposit` fails after the `SENDING_DEPOSIT` step, keep the stored record until you know the outcome (see [When a deposit fails after it started sending](#when-a-deposit-fails-after-it-started-sending)). Any error before that step 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: keep the same params to retry a failed deposit, and create new params for a new deposit. |
| `onProgress` | `((AggProgress) -> Unit)?` | `null` | See [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts). |
| `autoReconnect` | `Boolean` | `false` | See [When the link expires](#when-the-link-expires). |
| `addressPoll` | `AggPollOptions` | `intervalMs = 2_000`, `timeoutMs = 60_000` | How to wait for the deposit addresses, in milliseconds. |

`deposit` returns an `AggDepositResult` with `txHash`, `depositAddress`, `chainId` and `token` (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 `AggException.UnsupportedDepositToken`.
* When `token` names more than one, it fails with `AggException.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 a deposit fails after it started sending

Once `deposit` reports `SENDING_DEPOSIT`, it sends the transfer with `portal.sendAsset`, and a failure from there on is returned unchanged: the transfer may or may not have been broadcast. Some of these failures show that nothing was signed, such as a declined signing approval; treat the rest as unknown. A failure before `SENDING_DEPOSIT`, such as `MissingRpcUrl`, `InvalidAmount`, `UnsupportedDepositToken`, `AmbiguousDepositToken` or `DepositAddressesTimeout`, means nothing was sent.

1. **Check whether the transfer went out**, for example on the chain. A transfer missing from `listActivity(AggListActivityParams(type = AggActivityType.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.** 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/android/guide/idempotency-keys.md#handle-a-rejection): a `PortalException.Mpc.MpcResultError` whose `error.isIdempotencyRejection()` is `true`.
4. **Remove the record once the outcome is settled**: after a successful retry, an `IDEMPOTENT_REQUEST_ALREADY_COMPLETED` 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 `IDEMPOTENT_REQUEST_IN_PROGRESS` and any other error from a retry, which means this retry sent nothing while the first attempt's outcome is still unknown.

```kotlin theme={null}
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.predictionmarkets.AggDepositParams
import io.portalhq.android.utils.PortalIdempotencyErrorId
import io.portalhq.android.utils.errors.isIdempotencyRejection
import java.time.Duration
import java.time.Instant

suspend fun retryDeposit(store: PendingOperationStore, storeKey: String, record: Map<String, String>) {
    // Portal remembers a key for at least 24 hours; after that, a retry could send the deposit again.
    val age = Duration.between(Instant.parse(record.getValue("createdAt")), Instant.now())
    if (age >= Duration.ofHours(24)) {
        throw CheckTheChainFirst(storeKey) // your app's own exception
    }

    val params = AggDepositParams(
        chainId = record.getValue("chainId"),
        token = record.getValue("token"), // the token's address
        amount = record.getValue("amount"),
        idempotencyKey = record.getValue("idempotencyKey"),
    )
    portal.predictionMarkets.agg.deposit(params)
        .onSuccess { runCatching { store.remove(storeKey) } } // sent
        .onFailure { error ->
            val rejection = error as? PortalException.Mpc.MpcResultError
            val id = rejection?.takeIf { it.error.isIdempotencyRejection() }?.id
            when (id) {
                PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_IN_PROGRESS ->
                    println("Still processing. Retry later with the same key.")
                PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_ALREADY_COMPLETED -> {
                    println("Already broadcast. Don't send it again.")
                    runCatching { store.remove(storeKey) } // the first transfer went out
                }
                null ->
                    // This retry sent nothing, but the first attempt's outcome is still unknown:
                    // keep the stored record and retry later with the same key.
                    println("Unconfirmed: ${error.message}. Retry with the same key once the cause is fixed.")
                else ->
                    println("Unconfirmed ($id). Check the chain before sending under a new key.")
            }
        }
}
```

> [!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 `partially_filled` (`AggExecutionState.FILLED` or `AggExecutionState.PARTIALLY_FILLED`), 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):

```kotlin theme={null}
import io.portalhq.android.api.data.agg.AggMode
import io.portalhq.android.api.data.agg.AggQuote
import io.portalhq.android.predictionmarkets.AggBuyParams
import io.portalhq.android.predictionmarkets.AggException
import io.portalhq.android.predictionmarkets.AggHelperStep
import io.portalhq.android.predictionmarkets.AggSellParams
import java.time.Instant
import java.util.UUID

suspend fun buyOutcome(store: PendingOperationStore, outcomeId: String, mode: AggMode = AggMode.LIVE) {
    val storeKey = "agg-fill:${UUID.randomUUID()}"
    val placeholder = mapOf("outcomeId" to outcomeId, "mode" to mode.value, "createdAt" to Instant.now().toString())
    // A placeholder before anything is sent: if it can't be stored, don't trade.
    store.save(storeKey, placeholder)

    fun record(quote: AggQuote) = placeholder + mapOf("quoteId" to quote.quoteId, "expiresAt" to quote.expiresAt)

    val params = AggBuyParams(
        outcomeId = outcomeId,
        amount = "5", // USD to spend
        slippageBps = 100,
        mode = mode,
        onProgress = { event ->
            val quote = event.quote
            if (event.step == AggHelperStep.FILLING && quote != null) {
                // The fill is about to be sent: keep what following it would need.
                runCatching { store.save(storeKey, record(quote)) }
                    .onFailure { println("Couldn't store quote ${quote.quoteId}: $it") } // saved again below if the fill fails
            }
            // Each execution step carries a label that is ready to show.
            event.order?.steps?.forEach { println(it.label) }
        },
        autoReconnect = true,
    )

    val trade = portal.predictionMarkets.agg.buy(params).getOrElse { error ->
        if (error is AggException.OrderOutcomeUnknown) {
            // The fill may exist: keep the record (saving it again in case the save above failed) and follow it.
            runCatching { store.save(storeKey, record(error.quote)) }
                .onFailure { println("Couldn't store the quote: $it") }
        } else {
            // Any other error means the fill finished without trading, or was never sent.
            runCatching { store.remove(storeKey) }
        }
        throw error
    }

    // The fill reached a final state, so there is nothing left to follow.
    runCatching { store.remove(storeKey) }
    println("${trade.status.overallState} for quote ${trade.quote.quoteId}")
}

// A minimal example: before you use it in production, store and follow the fill as buyOutcome does.
suspend fun sellOutcome(outcomeId: String) {
    val trade = portal.predictionMarkets.agg.sell(AggSellParams(outcomeId = outcomeId, shares = "3")).getOrThrow()
    println(trade.status.overallState)
}
```

The `FILLING` save happens before the fill is sent, so it covers a crash or a cancellation, which throws `CancellationException` and leaves the record in place (see [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts)). `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` | `List<String>?` | Restrict routing to these venues, for example `listOf(AggVenue.POLYMARKET)`. |
| `mode` | `AggMode?` | `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` | `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 180 seconds). |

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

* **`AggException.QuoteNotTradable`**: the quote's `status` isn't `ok`, or a venue reported a warning. Nothing was traded. The exception carries the `quote`, with its `status`, `error` and `warnings`.
* **`AggException.OrderFailed`**: the fill ended in a final state other than filled or partially filled. The exception carries the final read as `status`, with `errorReason`.
* **`AggException.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 `AggException.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 exception records it. The exception 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). `FillNotFinalYet` stands for your app's own exception:

```kotlin theme={null}
import io.portalhq.android.api.data.agg.AggExecutionStatus
import io.portalhq.android.api.data.agg.AggMode
import io.portalhq.android.predictionmarkets.AggBuyParams
import io.portalhq.android.predictionmarkets.AggException
import kotlinx.coroutines.delay

/** Reads a fill until it is final, retrying transient failures, for up to [timeoutMs]. */
suspend fun followFill(quoteId: String, mode: AggMode, timeoutMs: Long = 600_000): AggExecutionStatus {
    val deadline = System.currentTimeMillis() + timeoutMs
    var waitMs = 1_000L

    while (System.currentTimeMillis() < deadline) {
        portal.predictionMarkets.agg.getOrder(quoteId, mode).fold(
            onSuccess = { response ->
                val status = response.data
                if (status.terminal) return status
                waitMs = (status.pollAfterMs ?: 1_000L).coerceIn(250L, 10_000L) // as the SDK does
            },
            onFailure = { error ->
                if (!isTransientAggError(error)) throw error
                waitMs = minOf(waitMs * 2, 30_000L)
            },
        )
        delay(waitMs)
    }

    // 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 FillNotFinalYet(quoteId)
}

suspend fun buyOnce(store: PendingOperationStore, outcomeId: String, amount: String, mode: AggMode): AggExecutionStatus {
    val result = portal.predictionMarkets.agg.buy(AggBuyParams(outcomeId = outcomeId, amount = amount, mode = mode))
    val unknown = result.exceptionOrNull() as? AggException.OrderOutcomeUnknown
        ?: return result.getOrThrow().status

    // Follow the existing fill instead of trading again.
    val quote = unknown.quote
    val storeKey = "agg-fill:${quote.quoteId}"
    runCatching { store.save(storeKey, mapOf("quoteId" to quote.quoteId, "mode" to mode.value, "expiresAt" to quote.expiresAt)) }
        .onFailure { println("Couldn't store the quote: $it") }

    val status = followFill(quote.quoteId, mode)
    runCatching { store.remove(storeKey) }
    // Final, but not necessarily traded: check status.overallState for filled or partially_filled.
    return status
}
```

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

When the exception's `fill` is `null`, 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 a failure there as unknown, not as "nothing traded". Check `listOrders(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` and its `orderId`.

```kotlin theme={null}
import io.portalhq.android.api.data.agg.AggCancelOrderRequest
import io.portalhq.android.api.data.agg.AggSide
import io.portalhq.android.api.data.agg.AggVenue
import io.portalhq.android.predictionmarkets.AggPlaceLimitOrderParams

suspend fun placeAndCancel(venueMarketOutcomeId: String) {
    val agg = portal.predictionMarkets.agg
    val order = agg.placeLimitOrder(
        AggPlaceLimitOrderParams(
            venue = AggVenue.POLYMARKET,
            venueMarketOutcomeId = venueMarketOutcomeId,
            side = AggSide.BUY,
            price = "0.42", // USD per share
            shares = "10",
        ),
    ).getOrThrow()
    println("Order ${order.orderId} is ${order.status}")

    val cancelled = agg.cancelOrder(AggCancelOrderRequest(orderId = order.orderId)).getOrThrow().data
    println("Cancel ${cancelled.status}")
}
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `venue` | `String` | | The venue of the market, for example `AggVenue.POLYMARKET`. |
| `venueMarketOutcomeId` | `String` | | `venueMarketOutcomes[].id` of a market on that venue. |
| `side` | `AggSide` | | `AggSide.BUY` or `AggSide.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` | `Boolean?` | `null` | Place the order only if it rests on the book instead of trading at once. |
| `expiresAt` | `String?` | `null` | When the order expires. Required with `GTD`. |
| `clientOrderId` | `String?` | `null` | 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 less than 1. Anything else fails with `AggException.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 failure is an `IOException` (no answer) or a `JsonParseException` (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(AggListOrdersParams(orderType = AggOrderType.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 list when nothing is eligible. Paper positions are not included.

```kotlin theme={null}
import io.portalhq.android.predictionmarkets.AggRedeemAllParams

val batches = portal.predictionMarkets.agg.redeemAll(AggRedeemAllParams(autoReconnect = true)).getOrThrow()

for (batch in batches) {
    for (result in batch.results) {
        println("${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(AggListActivityParams(type = AggActivityType.REDEEM))` first.

To redeem specific positions, call `redeemPositions(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):

```kotlin theme={null}
import io.portalhq.android.api.data.agg.AggTokenSymbol
import io.portalhq.android.predictionmarkets.AggException
import io.portalhq.android.predictionmarkets.AggHelperStep
import io.portalhq.android.predictionmarkets.AggWithdrawParams
import io.portalhq.android.utils.generateIdempotencyKey
import java.time.Instant

suspend fun withdrawToBase(store: PendingOperationStore) {
    var reachedWithdrawing = false
    val requestId = generateIdempotencyKey() // a UUID
    val storeKey = "agg-withdrawal:$requestId"
    val record = mapOf(
        "requestId" to requestId,
        "amount" to "10", // no more decimals than the token has, or withdraw refuses it
        "tokenSymbol" to AggTokenSymbol.USDC,
        "destinationChainId" to "eip155:8453",
        "createdAt" to Instant.now().toString(),
        // 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.
    store.save(storeKey, record)

    val params = AggWithdrawParams(
        amount = record.getValue("amount"),
        tokenSymbol = AggTokenSymbol.USDC,
        destinationChainId = record.getValue("destinationChainId"),
        requestId = requestId,
        onProgress = { event ->
            // Mark the record sent before the withdrawal is created, and keep its id once known.
            val marked = record + ("sent" to "true")
            if (event.step == AggHelperStep.WITHDRAWING) {
                reachedWithdrawing = true
                runCatching { store.save(storeKey, marked) }
                    .onFailure { println("Couldn't mark the withdrawal: $it") }
            }
            val withdrawal = event.withdrawal
            if (event.step == AggHelperStep.POLLING_WITHDRAWAL && withdrawal != null) {
                runCatching { store.save(storeKey, marked + ("withdrawalId" to withdrawal.withdrawalId)) }
                    .onFailure { println("Couldn't store the withdrawal id: $it") }
            }
        },
        autoReconnect = true,
    )

    val withdrawal = portal.predictionMarkets.agg.withdraw(params).getOrElse { error ->
        // 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 || error is AggException.WithdrawalFailed) {
            runCatching { store.remove(storeKey) }
        }
        throw error
    }

    runCatching { store.remove(storeKey) }
    println("Withdrawal ${withdrawal.withdrawalId} is ${withdrawal.status}")
}
```

`AggWithdrawParams` takes:

| Parameter | Type | Default | Description |
| - | - | - | - |
| `amount` | `String` | | A decimal string in `tokenSymbol`, with no more decimals than the token has. More decimals fail with `AggException.InvalidAmount`, and nothing is sent. |
| `tokenSymbol` | `String` | | The token to withdraw, for example `AggTokenSymbol.USDC`. |
| `destinationChainId` | `String` | | The CAIP-2 chain to withdraw to. |
| `destinationAddress` | `String?` | `null` | 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` | `intervalMs = 5_000`, `timeoutMs = 600_000` | How to read the withdrawal, in milliseconds. |

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

* **`AggException.WithdrawalNotViable`**: the preview didn't price as `quoted`. Nothing was sent. The exception carries the `preview`, with its `pricingStatus` and `unviableReason`.
* **`AggException.WithdrawalFailed`**: the withdrawal ended `failed`. The exception carries the `withdrawal`, with its `errorMessage`.
* **`AggException.WithdrawalOutcomeUnknown`**: the withdrawal may exist. It is returned when the last attempt to create it got no definite answer (no answer, a 5xx, or a response that didn't decode), or when reading it failed or timed out after it was created. A cancellation is thrown as `CancellationException`.
* **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` returns. 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 or `AGG_LINK_REQUIRED`, or by a reconnect that failed, and that refusal is returned 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` as below, and don't create new params until that is resolved.

### When the outcome of a withdrawal is unknown

After `AggException.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 exception carries a `withdrawal`, it was created: read `getWithdrawal(withdrawalId)`.
* When `withdrawal` is `null`, creating it got no definite answer: send `createWithdrawal(request)` again with the exception'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). `WithdrawalNotFinalYet` stands for your app's own exception:

```kotlin theme={null}
import io.portalhq.android.api.data.agg.AggWithdrawal
import io.portalhq.android.api.data.agg.AggWithdrawalRequest
import io.portalhq.android.api.data.agg.AggWithdrawalStatus
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay

/** Follows a withdrawal that may exist until it is final, for up to [timeoutMs]. */
suspend fun followWithdrawal(
    request: AggWithdrawalRequest,
    withdrawal: AggWithdrawal?,
    timeoutMs: Long = 1_800_000,
): AggWithdrawal {
    val agg = portal.predictionMarkets.agg
    val finalStatuses = setOf(AggWithdrawalStatus.COMPLETED, AggWithdrawalStatus.PARTIAL, AggWithdrawalStatus.FAILED)
    val deadline = System.currentTimeMillis() + timeoutMs
    var withdrawalId = withdrawal?.withdrawalId
    var waitMs = 5_000L

    while (System.currentTimeMillis() < deadline) {
        try {
            // Same requestId: Agg returns the original withdrawal instead of creating another.
            val id = withdrawalId
                ?: agg.createWithdrawal(request).getOrThrow().data.withdrawalId.also { withdrawalId = it }

            val latest = agg.getWithdrawal(id).getOrThrow().data
            if (latest.status in finalStatuses) return latest
            waitMs = 5_000L
        } catch (error: Exception) {
            if (error is CancellationException || !isTransientAggError(error)) throw error
            waitMs = minOf(waitMs * 2, 60_000L)
        }
        delay(waitMs)
    }

    // 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 WithdrawalNotFinalYet(request.requestId)
}

// After withdraw(params) fails:
// val error = result.exceptionOrNull()
// if (error is AggException.WithdrawalOutcomeUnknown) {
//     val final = followWithdrawal(error.request, error.withdrawal)
//     runCatching { 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 coroutine 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: the amount times 10 to the power of the token's decimals, which `quoteWithdrawable(AggWithdrawableQuoteRequest(tokenSymbol = …, destinationChainId = …))` returns as `decimals`. `withdraw` refuses an amount with more decimals than the token has, so this is always exact. When you have the `WithdrawalOutcomeUnknown` exception, its `request.amountRaw` is the exact value.
3. Call `followWithdrawal(request, null)` with it, 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(AggListActivityParams(type = AggActivityType.WITHDRAWAL))` shows no matching withdrawal, drop the record. Show the user a pending withdrawal, not a failed one, while a record exists. A `409` other than `AGG_LINK_REQUIRED` means Agg already holds a withdrawal under this `requestId` with different parameters, usually a wrongly computed `amountRaw`: find it in `listActivity(AggListActivityParams(type = AggActivityType.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(AggListActivityParams(type = AggActivityType.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` | `((AggProgress) -> Unit)?` | Called at each step, from inside the helper. Keep it quick, and switch to the main thread before you update your UI. An exception it throws is logged and the helper continues. |
| `autoReconnect` | `Boolean` | 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` (an `AggHelperStep`), and the fields the helper knows at that point: `quote`, `fill`, `order`, `txHash`, `withdrawalPreview` and `withdrawal`.

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

To stop a helper, cancel the coroutine that runs it, for example with `job.cancel()` or by leaving its `lifecycleScope` or `viewModelScope`. The helper then throws `CancellationException` instead of returning a `Result`. A request already sent is never undone or repeated:

* A `deposit` cancelled after the `SENDING_DEPOSIT` step may have broadcast the transfer: retry it with the same params, as in [When a deposit fails after it started sending](#when-a-deposit-fails-after-it-started-sending).
* A `buy`, `sell` or `withdraw` cancelled after the fill or withdrawal was sent may have left it in place. 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`.

```kotlin theme={null}
// buyOutcome stores the quote at the FILLING step, so a cancelled fill can be followed.
val buyJob = lifecycleScope.launch {
    buyOutcome(store, outcomeId)
}

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

`AggPollOptions` takes an `intervalMs` and a `timeoutMs`. While polling, a helper reads through up to 5 transient failures in a row: a 429, 502, 503 or 504, or an `IOException`, such as a timeout or a lost connection. Any other failure, such as a 500, a 4xx or a response that didn't decode, ends the wait. A wait that runs out fails with `AggException.DepositAddressesTimeout` (nothing was sent, so `deposit` can be called again), or ends in `OrderOutcomeUnknown` or `WithdrawalOutcomeUnknown` with no `cause` and the last read in `last`.

## Handling errors

Most failures are one of three kinds:

* **`AggException`**: a request the SDK refused to send, or a helper outcome. It is a sealed class: match its subclasses with `when`; each carries the context of that case.
* **A failed Portal API request**: a `PortalException.Api.HttpBadRequest` (400), `HttpUnauthorized` (401) or `HttpRequestFailed` (any other status), with the response's `rawBody` and the request's `traceId`. A request that got no answer fails with an `IOException`, and a response that didn't decode with a `JsonParseException`. `AggApiError.from(error)` reads the HTTP `status`, Portal's `id`, the `message`, Agg's `code` and `fields`, and the `traceId`. It returns `null` when there was no HTTP answer or when the response didn't decode.
* **Errors passed through unchanged**: `CancellationException` when the calling coroutine is cancelled (thrown, not returned in the `Result`; see [Progress, cancellation and timeouts](#progress-cancellation-and-timeouts)), a `PortalException.Credentials`, a failure to sign the link challenge in `connect`, and any failure of the deposit's `sendAsset`, such as a declined approval, an [idempotency rejection](https://docs.portalhq.io/sdks/android/guide/idempotency-keys.md#handle-a-rejection) or a `PortalException.Provider.InvalidIdempotencyKey`.

```kotlin theme={null}
import com.google.gson.JsonParseException
import io.portalhq.android.predictionmarkets.AggApiError
import io.portalhq.android.predictionmarkets.AggException
import java.io.IOException

fun describeAggFailure(error: Throwable): String {
    if (error is AggException.AmbiguousDepositToken) {
        return "Choose one of these token addresses: ${error.candidates.joinToString { it.address }}"
    }
    if (error is AggException) {
        return error.message.orEmpty()
    }

    val apiError = AggApiError.from(error)
    if (apiError != null) {
        return when {
            apiError.isLinkRequired -> "Link the wallet again with connect()."
            apiError.isAccountAbstractionUnsupported -> "Agg needs a Portal client without account abstraction."
            // 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.
            apiError.status == 403 -> "Request refused (403, trace ${apiError.traceId ?: "none"}): ${apiError.message.orEmpty()}"
            else -> "Request failed (${apiError.status ?: "no status"}, trace ${apiError.traceId ?: "none"})"
        }
    }

    if (error is IOException || error is JsonParseException) {
        return "No usable answer. The request may still have been processed."
    }
    return "Something went wrong."
}
```

Every `AggException` subclass:

| Subclass | 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 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 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. |
| `QuoteNotTradable` | The quote isn't `ok`, or a venue reported a warning. 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`. |
| `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`. |
| `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` | `AggApiError` property | What to do |
| - | - | - |
| `AGG_LINK_REQUIRED` | `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` | `isAccountAbstractionUnsupported` | The client is account-abstracted. Everything except discovery and market data is unavailable, `isConnected()` included. |
| `AGG_SESSION_REFRESH_IN_PROGRESS` | `isSessionRefreshInProgress` | Another request is renewing the user's Agg session. The SDK retries every call after 0.5, 1 and 2 seconds before returning this error. Retry after a moment, except `withdraw` after its `WITHDRAWING` step: follow the withdrawal. |
| `INTEGRATION_RESPONSE_SCHEMA_DRIFT` | `isSchemaDrift` | Agg changed a response shape. Treat it as an outage until Portal adapts. A request that changes state may still have been processed. |

`AggApiError.isRateLimit` is `true` for a `429`. 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 the `traceId` from `AggApiError.from(error)`, or from the `PortalException.Api` exception, 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 in responses, such as a market's `status`, a fill's `overallState` or a withdrawal's `status`, are plain `String`s, so a value Agg adds later still decodes instead of failing the response. The known values are constants on objects such as `AggMarketStatus`, `AggQuoteStatus`, `AggVenue`, `AggTokenSymbol`, `AggExecutionState` and `AggWithdrawalStatus`, for example `AggVenue.POLYMARKET`. Compare against the known constants, and add a fallback for the rest. An activity item of a type the SDK doesn't know decodes as `AggActivityItem.Unknown`, with its `type` and the `raw` JSON. Request options such as `AggMode`, `AggSide`, `AggTimeInForce` and the sort and type filters are closed Kotlin 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 a `Result` and keeps the request's failure 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 = AggOrderType.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` |

```kotlin theme={null}
val balances = portal.predictionMarkets.agg.getBalances(sync = true).getOrThrow().data

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

`Agg` is an `open` class, and all of its methods are `open`. To use your own implementation in tests, have your code take an `Agg` instead of reading `portal.predictionMarkets.agg` directly, and pass a subclass or a mock.

## 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 a `deposit` that failed after its `SENDING_DEPOSIT` step 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. **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/android/guide/idempotency-keys.md)
* Approve signing requests with [custom signature hooks](https://docs.portalhq.io/sdks/android/guide/add-custom-signature-hooks.md)


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