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 PortalSwift 8.2.0 or later.Overview
Withportal.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
- Helpers (
connect,isConnected,deposit,buy,sell,placeLimitOrder,redeemAllandwithdraw) 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 anAggResponsewhosedataholds the result. The same methods are also onportal.api.agg. See Low-level APIs.
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)
- A properly initialized Portal client with a wallet (see Getting started and Create a wallet)
- An
rpcConfigentry for every chain the wallet signs or sends on.connectsigns on Polygon (eip155:137) by default, anddepositsends on the chain you deposit from. When you don’t passwithRpcConfig, Portal’s defaultrpcConfigcovers 11 chains, Polygon and Base included. AwithRpcConfigyou pass replaces the default entirely (see Initializing Portal). - Gas on the wallet for the chain you deposit from
portal instance:
Quick start
The shortest path from a new user to a first trade. Each step has its own section below.getBalances(sync: true, mode: nil) before the first trade. To try trading without real funds, pass mode: .paper to buy (see Buying and selling).
Discovering markets
Agg models prediction markets as events, markets and outcomes (see Markets, events and outcomes). You trade an outcome, identified byvenueMarketOutcomes[].id on a market. Discovery works before the wallet is linked.
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.
Linking the wallet
Before a user can fund or trade, link their Portal wallet to their Agg account withconnect(). 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
rpcConfigentry (AggError.missingRpcUrl), - the client has no EVM address (
AggError.noAddress), or - the challenge names an address other than the wallet’s own (
AggError.addressMismatch).
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).
When the link expires
Portal keeps the user’s Agg session and refreshes it, but it can still expire. Any linked call then fails withAGG_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 runsconnectand 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
connecton thisPortalinstance, or on Polygon when there hasn’t been one, for example after the app restarts. Keep Polygon (eip155:137) in yourrpcConfig. OtherwisereconnectFailedwrapsmissingRpcUrl: callconnect(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.reconnectFailedinstead of asking the user to sign again: runconnect(), then call the helper again. The exception iswithdrawafter itswithdrawingstep, where an earlier attempt may have created the withdrawal: follow it instead (see Withdrawing).
autoReconnect applies to helpers only. The 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:
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.
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:
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:
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:
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
tokennames no token Agg takes onchainId, it fails withAggError.unsupportedDepositToken. - When
tokennames more than one, it fails withAggError.ambiguousDepositToken, whosecandidateslist the matches with theirsymbol,addressanddecimals: pass theaddressof the one to send. - When Agg lists the same address more than once with different
decimals, it also fails withambiguousDepositToken, 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.
When the outcome of a deposit is unknown
Once the transfer has started, any failure to get its transaction hash isAggError.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.
- 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. - Retry only with the same
idempotencyKeyuntil 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. - 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, which arrives as theunderlyingErrorof a newdepositOutcomeUnknown. - Remove the record once the outcome is settled: after a successful retry, a
requestAlreadyCompletedrefusal (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, includingrequestInProgressand any other error from a retry, which means this retry sent nothing while the first attempt’s outcome is still unknown.
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:
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:
Both also take
onProgress and autoReconnect (see Progress, cancellation and timeouts). They fail with:
AggError.quoteNotTradable: the quote’sstatusisn’tok, a venue reported a warning, or Agg attached anerror. Nothing was traded. The error carries thequote, with itsstatus,errorandwarnings.AggError.orderFailed: the fill ended in a final state other than filled or partially filled. The error carries the final read asstatus, witherrorReason.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
AfterAggError.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. MyAppError stands for your app’s own error type:
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), 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.
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.
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.
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:
AggWithdrawParams takes:
It also takes
onProgress and autoReconnect. It fails with:
AggError.withdrawalNotViable: the preview didn’t price asquoted. Nothing was sent. The error carries thepreview, with itspricingStatusandunviableReason.AggError.withdrawalFailed: the withdrawal endedfailed. The error carries thewithdrawal, with itserrorMessage.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
withdrawingstep, 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 meansdestinationAddressisn’t on your allowlist.
withdraw sends the same request again, with the same requestId, up to 3 attempts in all.
When the outcome of a withdrawal is unknown
AfterAggError.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: readgetWithdrawal(withdrawalId:). - When
withdrawalisnil, creating it got no definite answer: sendcreateWithdrawal(request:)again with the error’srequest, then read it. The request carries the samerequestId, so Agg returns the original withdrawal instead of creating a second one.
isTransientAggError from Keeping what recovery needs:
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:
- Build an
AggWithdrawalRequestfrom what you stored: the samerequestId,tokenSymbol,destinationChainIdanddestinationAddress. A request with changed parameters is refused, and arequestIdcan’t be combined withmax. - Pass the amount in base units as
amountRaw, exactly as the first request sent it.withdrawrounds the amount down to the token’s decimals, so pass an amount with no more decimals than the token has:amountRawis then the amount times 10 to the power of the token’s decimals, whichquoteWithdrawable(request: AggWithdrawableQuoteRequest(tokenSymbol:destinationChainId:))returns asdecimals. Or computeamountRawup front and store it. When you have thewithdrawalOutcomeUnknownerror, itsrequest.amountRawis the exact value. - Call
followWithdrawal(request:withdrawal:)with it andnil, and remove the record once it returns a final status.
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.
Progress, cancellation and timeouts
Every helper exceptconnect and isConnected takes these parameters:
Each
AggProgress event carries a step, and the fields the helper knows at that point: quote, fill, order, txHash, idempotencyKey, withdrawalPreview and withdrawal.
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:
depositfinishes a send it has started, and returns its result even when the task was cancelled.- A
buy,sellorwithdrawcancelled 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: thequoteIdfrom thefillingevent withfollowFill, or the withdrawal’srequestIdwithcreateWithdrawal. - A
placeLimitOrderorredeemAllcancelled mid-request can leave the order or the redemption in place: checklistOrdersorlistPositions.
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 (aPortalRequestsError, aURLErroror aDecodingError) asunderlyingErrorwith the request’straceId. The other Portal APIs throw the transport’s error itself, so matchPortalRequestsErroronunderlyingError.AggApiError.from(_:)reads the HTTPstatus, Portal’sid, themessage, Agg’sdetails(codeandfields) and thetraceId. It returnsnilwhen there was no HTTP answer, for example a lost connection, or when the response didn’t decode. - Errors passed through unchanged:
CancellationErroror aURLErrorwith code.cancelled(see Progress, cancellation and timeouts), aPortalIdempotencyErrorfor anidempotencyKeyPortal can’t accept, aPortalCredentialError, a failure to sign the link challenge inconnect, and a deposit send that failed before anything could be broadcast, such as a declined approval, aPortalMpcErrorlikeINSUFFICIENT_FUNDS, or a failed request to build the transfer. These carry no trace id.
AggError case:
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.
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.
Quote the
traceId from AggApiError.from(_:), or from the AggRequestError, when you report a failure to Portal support.Values Agg may add
Statuses, venues and token symbols, such asAggMarketStatus, 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 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.
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.
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
- Store what recovery needs in durable storage before the request: the
idempotencyKeyfordeposit, thequoteId(from thefillingevent) andmodeforbuyandsell, and therequestIdand parameters forwithdraw - Never repeat
buy,sellorwithdrawafter an outcome-unknown error or a cancellation, norwithdrawafter any error once it reached itswithdrawingstep: follow the existing fill or withdrawal instead, and retrydepositonly with the sameidempotencyKey - Bound every follow-up loop with a deadline, and retry only transient failures
- Pass token addresses, not symbols, when your app already knows them
- Preview the price before the user confirms a trade, for example with
createQuote, and passslippageBpstobuyandsell, which fill at once: Portal adds no trading guardrails - Check a quote before you offer it: a quote prices every venue, including ones this user can’t trade on, so
status == .okonly means pricing succeeded. Offer it only whenquote.status == .ok,(quote.warnings ?? []).isEmptyand(quote.error ?? "").isEmpty; otherwise show each warning’sreasonas is.buyandsellrun the same check and throwquoteNotTradable(see Trading on the integration page) - Turn on
autoReconnectso an expired Agg session costs the user one signature, not a failed action
Next Steps
- Set up the integration: Agg by Snag
- Retry transfers safely with idempotency keys
- Approve signing requests with custom signature hooks