Skip to main content
Portal’s React Native SDK lets your users trade prediction markets across Polymarket, Kalshi, Limitless and other venues through portal.predictionMarkets.agg. This guide covers discovering markets, linking the Portal wallet, funding the user’s Agg balance, trading, redeeming and withdrawing, and recovering safely when the outcome of a request is unknown.
portal.predictionMarkets requires @portal-hq/core 6.0.0 or later.

Overview

With portal.predictionMarkets.agg you can:
  • Discover events, markets and outcomes, with prices, order books and charts
  • Link the Portal wallet to the user’s Agg account with one signature
  • Fund the user’s Agg balance from the Portal wallet
  • Buy and sell outcomes, and place and cancel limit orders
  • Redeem winning positions and withdraw to a Portal address
The Agg by Snag integration page explains how Agg works: the managed balance, quotes and fills, and how venues settle. Two kinds of method are available:
  • Helpers (connect, isConnected, deposit, buy, sell, placeLimitOrder, redeemAll and withdraw) run a whole flow and resolve with its result.
  • API methods, one per Portal API route except self-custody signature submission (POST /orders/{quoteId}/signatures), resolve with the response wrapped as { data }. See Low-level APIs.
Chain IDs are CAIP-2, for example eip155:137 for Polygon.

Prerequisites

Before using Agg, ensure you have:
  • The Agg by Snag integration set up for your environment (see Setup)
  • A properly initialized Portal client with a wallet (see Getting started and Create a wallet)
  • A gatewayConfig entry for every chain the wallet signs or sends on. connect signs on Polygon (eip155:137) by default, and deposit sends on the chain you deposit from. The default gatewayConfig covers the 11 built-in chains, Polygon included. A custom gatewayConfig is used exactly as supplied (see Custom RPC configuration).
  • Gas on the wallet for the chain you deposit from
Everything except discovery and market data requires a Portal client without account abstraction. 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.
Live trading is real money and geo-restricted. Every venue blocks some countries, and geofencing your users is your responsibility. Read Geo restrictions and Compliance before you go live.
The examples in this guide use a portal instance:

Discovering markets

Agg models prediction markets as events, markets and outcomes (see Markets, events and outcomes). You trade an outcome, identified by venueMarketOutcomes[].id on a market. Discovery works before the wallet is linked.
Use search({ q, type: 'events' | 'markets' }) for free-text search, and getEvent(eventId) for one event. For prices, read getMidpoints(venueMarketIds), getOutcomeOrderbook(outcomeId, { depth }) and getChartBars({ venueMarketOutcomeId, to }). Every method is listed in Low-level APIs.

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.
connect(chainId?) signs on another EVM chain Agg supports when you pass its CAIP-2 ID. Nothing is signed when:
  • the chain has no gatewayConfig entry (MissingRpcUrl),
  • the client has no EVM address (NoAddress), or
  • the challenge names an address other than the wallet’s own (AddressMismatch).
With custom signature hooks, the link signature reaches your portal_signingRequested handler as a normal personal_sign request. Portal keeps the user’s Agg session and refreshes it, but it can still expire. Any linked call then fails with AGG_LINK_REQUIRED, and the fix is to run connect() again. isConnected() returns whether the client is linked, and false can also mean the session expired. Don’t rely on it alone: a call can still fail with AGG_LINK_REQUIRED after it returns true. Instead, pass autoReconnect: true to the helpers. On AGG_LINK_REQUIRED, a helper runs connect() and retries the refused call once. It links on the chain of the last successful connect() on this Portal instance, or on Polygon when there hasn’t been one, for example after the app restarts. Helpers refused together share one connect(), so the user signs once. A call refused for the link did nothing, so the retry can’t trade or send twice. autoReconnect applies to helpers only. The low-level APIs reject with AGG_LINK_REQUIRED and leave reconnecting to you. To unlink, call deleteLink().

Keeping what recovery needs

deposit(), buy(), sell() and withdraw() can fail with the outcome unknown: the transfer, fill or withdrawal may exist even though the call failed. To follow it instead of sending it again, your app needs values that exist only while the call runs, and it needs them after a crash or restart too. The SDK doesn’t persist them. Store them in durable storage your app owns, such as a database or encrypted storage, before the call that can create the operation: The examples in this guide use this interface for that storage. Implement it with your app’s own persistence:
Following an operation means polling it until it reaches a final state. Retry only transient failures, back off between attempts, and stop at a deadline while keeping the stored values, so you can check again later. The recovery examples use these helpers:

Funding the Agg balance

deposit() sends a token from the Portal wallet to the user’s Agg deposit address and resolves once the transfer is broadcast. It waits for the deposit addresses, since Agg creates them after the first link. This example uses the PendingOperationStore from Keeping what recovery needs:
When deposit() fails, keep the stored record until you know the outcome. Remove it only after a failure that means nothing was sent (see the note at the end of this section). The parameters: deposit() also takes the helper options. It resolves with { txHash, depositAddress, chainId, token, idempotencyKey }, where token is the token as Agg lists it on chainId. Agg credits the deposit once the transfer confirms. To see it, read getBalances({ sync: true }).

Choosing the token

A token is identified by its chain and address. A symbol is only a convenience, and one symbol can name several tokens on the same chain. deposit() never picks one by position:
  • When token names no token Agg takes on chainId, it fails with UnsupportedDepositToken.
  • When token names more than one, it fails with AmbiguousDepositToken. error.details.candidates lists the matches, with their symbol, address and decimals: pass the address of the one to send.
  • When Agg lists the same address more than once with different decimals, it also fails with AmbiguousDepositToken, and the candidates share one address. Passing that address fails the same way, so the token can’t be deposited until Agg’s listing is corrected.
Nothing is sent in any of these cases.

When the outcome of a deposit is unknown

Once the transfer has started, any failure to get its transaction hash is DepositOutcomeUnknown: the transfer may or may not have been broadcast. error.details carries the idempotencyKey, chainId, depositAddress, token and amount, and error.cause is the underlying failure. DepositOutcomeUnknown is deliberately conservative. The SDK raises it for every failure after it starts building the transfer, including failures from before anything is signed, for example when Portal can’t build the transaction. Read error.cause to tell these apart. error.details.token is the token the first attempt resolved to, so retry with token: error.details.token.address.
  1. Check whether the transfer went out, for example on the chain. A transfer missing from listActivity({ type: 'deposit' }) or from the balance may not be credited yet, so neither proves it wasn’t broadcast.
  2. Retry only with the same idempotencyKey until you’ve confirmed the first transfer didn’t land. While Portal remembers the key, for at least 24 hours after the request was last updated, it won’t broadcast a second transfer under it.
  3. Read the retry’s refusal from error.cause. Portal can refuse the retry with an idempotency rejection, which arrives as the cause of a new DepositOutcomeUnknown.
deposit() rebuilds the transfer on every call, so Portal can refuse a retry with IDEMPOTENCY_KEY_REUSED when the rebuilt transfer differs. This is usual on Solana, whose transactions carry a new recent blockhash, and when Agg has issued a new deposit address. Send under a new key only once you’ve confirmed the first transfer didn’t land and can no longer land. For a deposit older than 24 hours, check the chain before retrying with any key.
Failures before the transfer starts, such as MissingRpcUrl, UnsupportedDepositToken, AmbiguousDepositToken or DepositAddressesTimeout, mean nothing was sent. An idempotencyKey that Portal can’t accept is also rethrown unchanged, as a PortalIdempotencyError, because it is refused before anything is signed.
If you show a deposit address yourself, read it with getDepositAddresses() right before you show it. Agg can reassign the deposit wallet of an inactive user, so a cached address can go stale. deposit() reads it on every call.

Buying and selling

buy() and sell() quote an outcome, fill the quote at once, and wait for the fill to finish. They resolve with { quote, fill, status }, where status is the final read of the fill. status.overallState is filled or partially_filled, and status.orders says how much filled. This example uses the PendingOperationStore from Keeping what recovery needs:
onProgress can’t delay the helper, so the save above may still be running when the fill request is sent. OrderOutcomeUnknown also carries the quoteId, so save it again there, as the next example does. Both also take the helper options. They fail with:
  • QuoteNotTradable: the quote’s status isn’t ok, or a venue reported a warning. Nothing was traded. error.details.quote carries the status, error and warnings.
  • OrderFailed: the fill ended in a final state other than filled or partially_filled. error.details.status is the final read, with errorReason.
  • OrderOutcomeUnknown: the fill may exist, but the helper couldn’t see it finish, for example after a timeout, an abort, a lost connection or a 5xx on the fill request.
  • An unchanged API error: Portal or Agg refused the quote or the fill with a definite answer, such as a 4xx. Nothing was traded. A 403 on a trade usually means the user’s location is blocked.

When the outcome of a fill is unknown

After OrderOutcomeUnknown, never call buy() or sell() again: the first fill may still execute. Follow it with getOrder(quoteId, { mode }) instead, using the same mode as the trade: neither the quote nor the error records it. error.details carries the quote, the fill when it was placed, and last, the last read of the fill. This example uses PendingOperationStore, sleep and isTransientAggError from Keeping what recovery needs:
After a restart, call followFill() with each stored quoteId and mode. When error.details.fill is absent, the fill request itself got no definite answer, so the fill may or may not exist. What getOrder() returns for a quote that was never filled isn’t specified, so treat an error there as unknown, not as “nothing traded”. Check listOrders({ quoteId, mode }) and the user’s activity before you trade again.

Limit orders

placeLimitOrder() places a resting order from a decimal price and size, and resolves with the order once it is placed. Cancel it with cancelOrder() and its orderId.
Before sending, the SDK checks only that price and shares are positive decimal strings with at most 6 decimal places, not counting trailing zeros, and that price is below 1. Anything else fails with InvalidAmount, and nothing is sent. The SDK doesn’t check the market’s tick size or minimum size; the venue enforces those.
Polymarket’s $1 minimum for orders that trade at once (price × shares) is applied after submission. placeLimitOrder() resolves, and the order later moves from pending to failed, with the reason in errorMessage on listOrders(). Check price × shares in your UI before submitting.
Unlike buy() and sell(), placeLimitOrder() doesn’t wait for the order to fill or classify an ambiguous failure. After an AggNoResponseError or a 5xx, the order may have been placed: check listOrders({ orderType: 'limit' }) before placing it again.

Redeeming winnings

redeemAll() redeems every live position whose redeemStatus is eligible, in batches of 20, and resolves with each batch’s result. It skips holdings on a losing outcome, and resolves with an empty list when nothing is eligible. Paper positions are not included.
redeemAll() stops at the first failure or abort, and the results of batches that already went through are not returned. Check listPositions() and listActivity({ type: 'redeem' }) before you run it again. To redeem specific positions, call redeemPositions({ venueMarketOutcomeIds }) with up to 20 IDs of positions whose redeemStatus is eligible. It takes the venue’s own outcome ID: venueMarket.venueMarketOutcomes[].venueBreakdown[].venueMarketOutcomeId on a position from listPositions(). That is not the venueMarketOutcomes[].id you trade with, and it can’t be derived from an order.

Withdrawing

withdraw() moves funds out of the Agg balance and waits for the withdrawal to finish. It previews the withdrawal first and sends nothing unless the amount prices as quoted. It resolves with the withdrawal once its status is completed or partial. This example uses the PendingOperationStore from Keeping what recovery needs:
withdraw() also takes the helper options. It fails with:
  • WithdrawalNotViable: the preview didn’t price as quoted. Nothing was sent. error.details.preview carries the pricingStatus and unviableReason.
  • WithdrawalFailed: the withdrawal ended failed. error.details.withdrawal carries its errorMessage.
  • WithdrawalOutcomeUnknown: the withdrawal may exist. Any failure after that point, an abort included, ends here.
  • An unchanged API error: Portal or Agg refused the preview or the withdrawal with a definite answer, such as a 4xx. Nothing was withdrawn. A 403 here usually means destinationAddress isn’t on your allowlist.
When creating the withdrawal fails with a rate limit, a gateway error or no response, withdraw() sends the same request again, with the same requestId, up to 3 attempts in all. If every attempt was refused with a rate limit (429), the 429 is rethrown unchanged: Agg refused each attempt, so nothing was created.

When the outcome of a withdrawal is unknown

After WithdrawalOutcomeUnknown, never call withdraw() again. Without the same requestId it would create a second withdrawal, and with it, it would preview again, and the preview can refuse funds that are already on their way. Follow the existing withdrawal instead:
  • With error.details.withdrawal, it was created: poll getWithdrawal(withdrawalId).
  • Without it, creating it got no definite answer: send createWithdrawal(error.details.request) again, then poll it. The request carries the same requestId, so Agg returns the original withdrawal instead of creating a second one.
This example uses sleep and isTransientAggError from Keeping what recovery needs:
To resume after your app restarts, send createWithdrawal() with the request you stored: the same requestId (a UUID), tokenSymbol, destinationChainId and destinationAddress, and the amount in base units as amountRaw. quoteWithdrawable({ tokenSymbol, destinationChainId }) returns the token’s decimals for that destination. A requestId can’t be combined with max.
If the first request never reached Agg, createWithdrawal() creates the withdrawal now, without the preview withdraw() runs first. How long Agg keeps returning the original withdrawal for a requestId isn’t documented, so resume promptly, and check getWithdrawal() or listActivity({ type: 'withdrawal' }) before sending a stored request that is days old.

Progress, cancellation and timeouts

Every helper except connect and isConnected takes these options: Each progress event carries a step, and the fields the helper knows at that point: quote, fill, order, txHash, idempotencyKey, withdrawalPreview and withdrawal. Aborting before anything is sent rejects with the signal’s reason. A request already sent is never abandoned or repeated:
  • deposit() still resolves with the result once the transfer has started.
  • A fill or withdrawal that may exist ends in OrderOutcomeUnknown or WithdrawalOutcomeUnknown.
The poll options take intervalMs and timeoutMs. While polling, a helper reads through up to 5 transient failures in a row: a 429, 502, 503 or 504, or no response. Each request gives up after 120 seconds without an answer.

Handling errors

Most failures are one of three kinds:
  • AggError: a request the SDK refused to send, or a helper outcome. Check it with AggError.is(error, reason?) and branch on reason. details holds the context of each reason, and cause holds the failure that stopped the helper.
  • A failed Portal API request: an HttpError from the Portal API. AggApiError.from(error) reads its status, Portal’s id, message, Agg’s code and fields, and the traceId it was sent with. It also unwraps the cause of OrderOutcomeUnknown and WithdrawalOutcomeUnknown.
  • AggNoResponseError: the Portal API sent no usable answer, or none within 120 seconds. The request may or may not have been processed. AggApiError.from() also accepts it, returning only its traceId, so check for it first.
Other errors pass through unchanged: the signal’s abort reason, a PortalIdempotencyError for an idempotencyKey Portal can’t accept, a PortalCredentialError, and failures to read the wallet address or sign the link challenge in connect().
Use AggError.is(error), not instanceof. AggError is identified by a brand that works across copies of @portal-hq/core, so instanceof can return false for a real AggError. Only AggError has .is(). Check AggNoResponseError with instanceof, as in the example above.
Every AggError reason: Portal’s own refusals carry an id, exposed as AggErrorId: 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.
Quote traceId from AggApiError.from(error) when you report a failure to Portal support.

Low-level APIs

The helpers cover the common flows. Each Portal API route, except self-custody signature submission (POST /orders/{quoteId}/signatures), also has its own method, which resolves with { data } and rejects with the errors described in Handling errors, with no reconnecting, polling or retrying apart from the session-refresh retry above. See the endpoint reference for each route.
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.

Best practices

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

Next Steps