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
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, whosedataholds the result. The same methods are also onportal.api.agg. See Low-level APIs.
suspend function that returns a Kotlin Result: read it with getOrThrow(), getOrElse, onSuccess / onFailure or fold. Chain IDs are CAIP-2, 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)
- 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 passrpcConfig, Portal’s defaultrpcConfigcovers 11 chains, Polygon and Base included. AnrpcConfigyou pass replaces the default entirely (see Initializing Portal). - Gas on the wallet for the chain you deposit from
portal instance:
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(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.
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 (AggException.MissingRpcUrl), - the client has no EVM address (
AggException.NoAddress), or - the challenge names an address other than the wallet’s own (
AggException.AddressMismatch).
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).
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, 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 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. Otherwise the reconnect fails withMissingRpcUrl: 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 and returns that failure, as
connectreported it, instead 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 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:
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.
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:
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 after the SENDING_DEPOSIT step, keep the stored record until you know the outcome (see 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:
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
tokennames no token Agg takes onchainId, it fails withAggException.UnsupportedDepositToken. - When
tokennames more than one, it fails withAggException.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 a deposit fails after it started sending
Oncedeposit 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.
- 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. - 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. Portal refuses a retry under a key it has already seen (sent, still in progress or failed) with an idempotency rejection: a
PortalException.Mpc.MpcResultErrorwhoseerror.isIdempotencyRejection()istrue. - Remove the record once the outcome is settled: after a successful retry, an
IDEMPOTENT_REQUEST_ALREADY_COMPLETEDrefusal (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, includingIDEMPOTENT_REQUEST_IN_PROGRESSand 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 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:
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). 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:
AggException.QuoteNotTradable: the quote’sstatusisn’tok, or a venue reported a warning. Nothing was traded. The exception carries thequote, with itsstatus,errorandwarnings.AggException.OrderFailed: the fill ended in a final state other than filled or partially filled. The exception carries the final read asstatus, witherrorReason.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
AfterAggException.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. FillNotFinalYet stands for your app’s own exception:
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), 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.
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.
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.
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:
AggWithdrawParams takes:
It also takes
onProgress and autoReconnect. It fails with:
AggException.WithdrawalNotViable: the preview didn’t price asquoted. Nothing was sent. The exception carries thepreview, with itspricingStatusandunviableReason.AggException.WithdrawalFailed: the withdrawal endedfailed. The exception carries thewithdrawal, with itserrorMessage.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 asCancellationException.- 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
AfterAggException.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: readgetWithdrawal(withdrawalId). - When
withdrawalisnull, creating it got no definite answer: sendcreateWithdrawal(request)again with the exception’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. WithdrawalNotFinalYet stands for your app’s own exception:
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:
- 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: the amount times 10 to the power of the token’s decimals, whichquoteWithdrawable(AggWithdrawableQuoteRequest(tokenSymbol = …, destinationChainId = …))returns asdecimals.withdrawrefuses an amount with more decimals than the token has, so this is always exact. When you have theWithdrawalOutcomeUnknownexception, itsrequest.amountRawis the exact value. - Call
followWithdrawal(request, null)with it, and remove the record once it returns a final status.
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.
Progress, cancellation and timeouts
Every helper exceptconnect and isConnected takes these parameters:
Each
AggProgress event carries a step (an AggHelperStep), and the fields the helper knows at that point: quote, fill, order, txHash, withdrawalPreview and withdrawal.
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
depositcancelled after theSENDING_DEPOSITstep may have broadcast the transfer: retry it with the same params, as in When a deposit fails after it started sending. - A
buy,sellorwithdrawcancelled after the fill or withdrawal was sent may have left it in place. 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 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 withwhen; each carries the context of that case.- A failed Portal API request: a
PortalException.Api.HttpBadRequest(400),HttpUnauthorized(401) orHttpRequestFailed(any other status), with the response’srawBodyand the request’straceId. A request that got no answer fails with anIOException, and a response that didn’t decode with aJsonParseException.AggApiError.from(error)reads the HTTPstatus, Portal’sid, themessage, Agg’scodeandfields, and thetraceId. It returnsnullwhen there was no HTTP answer or when the response didn’t decode. - Errors passed through unchanged:
CancellationExceptionwhen the calling coroutine is cancelled (thrown, not returned in theResult; see Progress, cancellation and timeouts), aPortalException.Credentials, a failure to sign the link challenge inconnect, and any failure of the deposit’ssendAsset, such as a declined approval, an idempotency rejection or aPortalException.Provider.InvalidIdempotencyKey.
AggException subclass:
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.
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.
Quote the
traceId from AggApiError.from(error), or from the PortalException.Api exception, when you report a failure to Portal support.Values Agg may add
Statuses, venues and token symbols in responses, such as a market’sstatus, a fill’s overallState or a withdrawal’s status, are plain Strings, 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 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.
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
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
- 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 retry adepositthat failed after itsSENDING_DEPOSITstep only 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 - 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