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
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 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.
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
gatewayConfigentry for every chain the wallet signs or sends on.connectsigns on Polygon (eip155:137) by default, anddepositsends on the chain you deposit from. The defaultgatewayConfigcovers the 11 built-in chains, Polygon included. A customgatewayConfigis used exactly as supplied (see Custom RPC configuration). - 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.
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 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
gatewayConfigentry (MissingRpcUrl), - the client has no EVM address (
NoAddress), or - the challenge names an address other than the wallet’s own (
AddressMismatch).
portal_signingRequested handler as a normal personal_sign request.
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 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:
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:
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
tokennames no token Agg takes onchainId, it fails withUnsupportedDepositToken. - When
tokennames more than one, it fails withAmbiguousDepositToken.error.details.candidateslists 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 isDepositOutcomeUnknown: 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.
- 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. - 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 after the request was last updated, it won’t broadcast a second transfer under it. - Read the retry’s refusal from
error.cause. Portal can refuse the retry with an idempotency rejection, which arrives as thecauseof a newDepositOutcomeUnknown.
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.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’sstatusisn’tok, or a venue reported a warning. Nothing was traded.error.details.quotecarries thestatus,errorandwarnings.OrderFailed: the fill ended in a final state other thanfilledorpartially_filled.error.details.statusis the final read, witherrorReason.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
AfterOrderOutcomeUnknown, 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:
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.
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 asquoted. Nothing was sent.error.details.previewcarries thepricingStatusandunviableReason.WithdrawalFailed: the withdrawal endedfailed.error.details.withdrawalcarries itserrorMessage.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
destinationAddressisn’t on your allowlist.
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
AfterWithdrawalOutcomeUnknown, 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: pollgetWithdrawal(withdrawalId). - Without it, creating it got no definite answer: send
createWithdrawal(error.details.request)again, then poll it. The request carries the samerequestId, so Agg returns the original withdrawal instead of creating a second one.
sleep and isTransientAggError from Keeping what recovery needs:
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.
Progress, cancellation and timeouts
Every helper exceptconnect 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
OrderOutcomeUnknownorWithdrawalOutcomeUnknown.
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 withAggError.is(error, reason?)and branch onreason.detailsholds the context of each reason, andcauseholds the failure that stopped the helper.- A failed Portal API request: an
HttpErrorfrom the Portal API.AggApiError.from(error)reads itsstatus, Portal’sid,message, Agg’scodeandfields, and thetraceIdit was sent with. It also unwraps thecauseofOrderOutcomeUnknownandWithdrawalOutcomeUnknown. 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 itstraceId, so check for it first.
PortalIdempotencyError for an idempotencyKey Portal can’t accept, a PortalCredentialError, and failures to read the wallet address or sign the link challenge in connect().
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
- Store what recovery needs in durable storage before calling: the
idempotencyKeyfordeposit(), thequoteIdandmodeforbuy()andsell(), and therequestIdand parameters forwithdraw() - Never repeat a helper after an
OutcomeUnknownerror: follow the existing deposit, fill or withdrawal instead - Bound every follow-up loop with a deadline, and retry only transient failures
- Pass token addresses, not symbols, when your app already knows them
- Show the quote before the user confirms a trade: 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