portal.predictionMarkets.agg API. This guide covers linking the user’s wallet to Agg, discovering markets, funding the Agg balance, trading, redeeming and withdrawing.
portal.predictionMarkets requires @portal-hq/web 5.0.0 or later.Overview
Withportal.predictionMarkets.agg you can:
- Link the user’s Portal wallet to their Agg account with one signature
- Discover events, markets and outcomes, with live prices, order books and charts
- Fund the user’s Agg balance from their Portal wallet
- Buy and sell outcomes at the best price across venues, or place limit orders
- Redeem winning positions and withdraw to the user’s wallet
- Helpers (
connect,isConnected,deposit,buy,sell,placeLimitOrder,redeemAllandwithdraw) run a whole flow and resolve with its result. - Route 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. Amounts you pass to the helpers are decimal strings, such as '10' or '1.5'.
Prerequisites
Before using Agg, make sure you have:- A properly initialized Portal client with the iframe ready (
portal.onReady; see The onReady hook) - An active wallet with an EVM address (see Create a wallet)
- Gas on the wallet for the chain you deposit from
- Agg set up for your environment: an Agg app, trusted proxy, and the integration enabled in your Portal Dashboard. Follow Setup on the Agg integration page.
- An
rpcConfigentry for every chain the SDK signs or sends on: Polygon (eip155:137), whereconnectsigns by default, and every chain you deposit from. The defaultrpcConfigcovers the 13 built-in chains. An explicitrpcConfigreplaces the defaults rather than extending them. Without an entry, the helper fails withMissingRpcUrland nothing is signed or sent.
agg instance:
Discovering markets
Discovery works before the user links. An event, such as an election, groups markets, and each market has outcomes. You trade an outcome, identified byvenueMarketOutcomes[].id on its market.
nextCursor back as cursor while hasMore is true. Read an event’s markets from markets on getEventBootstrap, not from event.venueMarkets, which can be empty there. Continue with listMarkets({ venueEventId, cursor: markets.nextCursor }).
The other discovery methods are getEvent, listMarkets, search ({ q, type: 'events' | 'markets' }), listCategories, getVenueGeoPolicy and getAppConfig.
Linking the wallet
connect links the Portal wallet to the user’s Agg account. It asks the Portal API for a sign-in message, signs it with personal_sign on the chain you pass (Polygon, eip155:137, by default), and completes the link.
AddressMismatch otherwise). If you use signature approvals, the signature reaches your approval hook as a normal personal_sign.
isConnected() reports whether the client is linked, and deleteLink() unlinks it.
A linked user’s Agg session can still expire. Any call can then fail with the AGG_LINK_REQUIRED error id, even after isConnected() returned true. Run connect again and retry, or pass autoReconnect: true to a helper so it does that for you (see Progress, cancellation and reconnecting).
Market data and charts
getMidpoints(venueMarketIds)andgetOrderbooks(venueMarketIds)return live prices and books for a batch of markets. Each order book entry’srequestedMarketcarries thesizeStepRawandminSizeRawa limit order must respect.getOutcomeOrderbook(outcomeId)returns one outcome’s ladder and depth.getChartBarsreturns OHLCV bars for one outcome.getChartHistoryManifestreturns finalized history for long ranges as CDN chunks.
data can be empty while Agg prepares a series. Read meta.state, and while it is warming, call again after meta.retryAfterMs.
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. Following it instead of sending it again takes values that exist only while the call runs, and your app needs them after a reload or restart too. The SDK doesn’t persist them, and a variable or a log line doesn’t survive a reload. Store them in durable storage your app owns, such as your backend, before the call:
The examples below use this interface for that storage. Implement it with your app’s own persistence:
Funding the Agg balance
Trades draw from the user’s Agg balance.deposit sends a token from the Portal wallet to the user’s Agg deposit address. It waits for the deposit addresses, then sends the transfer and resolves once it’s broadcast. Agg credits it once it confirms. Once the transfer confirms, call getBalances({ sync: true }) to re-read the chains.
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.
PendingOperationStore from Keeping what recovery needs:
deposit fails, keep the stored record until you know the outcome. Remove it only after one of the failures below that send nothing.
token is the token’s contract address or its symbol, as Agg lists it for chainId. A symbol is a convenience and isn’t guaranteed to be unique. If it matches more than one token on the chain, deposit fails with AmbiguousDepositToken and sends nothing. Pass the address of one of details.candidates instead.
deposit sends nothing and fails with:
UnsupportedDepositTokenwhen Agg doesn’t take the token on that chainAmbiguousDepositTokenwhen the symbol matches several tokensDepositAddressesTimeoutwhen the deposit addresses aren’t ready in timeMissingRpcUrlwhenchainIdhas no RPC URL configuredInvalidAmountwhenamountisn’t positive or has more decimals than the token, not counting trailing zeros
idempotencyKey Portal can’t use is rethrown unchanged, as a PortalIdempotencyError, before anything is sent.
When a deposit’s outcome is unknown
If the transfer fails after it starts sending,deposit fails with DepositOutcomeUnknown: the transfer may or may not have been broadcast. details carries the idempotencyKey, chainId, depositAddress, token and amount.
- Check whether the transfer went out before sending it again, 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. - To retry, call
depositagain withdetails.idempotencyKey, or after a restart, with the record you stored. While Portal remembers the key, at least 24 hours after the request was last updated, it won’t broadcast a second transfer under it. It may refuse the retry instead: the refusal is the new error’scause, recognized byisIdempotencyRejection. See Handle a rejection for what each refusal means. - Use a new key only once you’ve confirmed the first transfer didn’t land and can no longer land.
Buying and selling
buy and sell quote an outcome across venues, fill the quote at once and wait for the fill to finish. buy takes the USD to spend as amount; sell takes the number of shares.
This example uses the PendingOperationStore from Keeping what recovery needs:
onProgress isn’t awaited, so the save may still be running when the fill request is sent. OrderOutcomeUnknown also carries the quoteId, so the example saves it again there and rethrows the error: show the trade as pending and follow it with getOrder(quoteId, { mode }) as described below. Never call buy or sell again for it.
After a restart, follow each stored record: call getOrder(quoteId, { mode }) until its terminal is true, waiting pollAfterMs between reads when Agg sends it, then remove the record. If the fill request never reached Agg, what getOrder returns for that quote isn’t specified: treat an error there as unknown rather than as nothing traded, and check listOrders({ quoteId, mode }) before trading again.
The result holds the quote, the fill, and the final read of the order as status. Its overallState and orders[] tell you how much filled.
Pass
mode: 'paper' to simulate the trade, and venues to restrict routing to some venues. getOrder reads live orders unless you pass { mode: 'paper' }, so a paper fill is only found when you pass the same mode. The quote doesn’t record its mode: keep the one you traded in.
To show the user a price before they confirm, call the route methods yourself: createQuote, then createOrder({ quoteId }), then poll getOrder(quoteId), passing the same mode to each. Before offering a quote, check that its status is ok and that it has no warnings. Quotes expire quickly; see Trading on the integration page.
Limit orders
placeLimitOrder places a resting order on one venue from a decimal price and size. Pass the market’s venue and the outcome’s id.
priceis USD per share, below1, with at most 6 decimals, not counting trailing zeros.sharesalso takes at most 6 decimals, not counting trailing zeros. Size orders in multiples of the market’ssizeStepRawand at least itsminSizeRaw, whichgetOrderbooksreturns.timeInForcedefaults toGTC.expiresAtis required withGTD.listOrders({ orderType: 'limit' })lists the user’s limit orders. Cancel an open one by itsid.
listOrders before placing it again.
Redeeming winnings
listPositions lists the user’s positions. Once a market resolves, redeemAll redeems every position whose redeemStatus is eligible, and returns one result per batch of up to 20. Holdings on a losing outcome are left out, and the list is empty when nothing is eligible.
redeemAll redeems live positions only, not paper ones. It stops at the first failure or abort: the call rejects, and the results of the batches before it, which may have redeemed, aren’t returned. Read listPositions again before you redeem 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 quote and trade with, which placeLimitOrder also calls venueMarketOutcomeId, and it can’t be derived from an order.
Withdrawing
withdraw withdraws from the Agg balance to a chain and waits for the withdrawal to finish. It previews the withdrawal first, and sends nothing unless the preview’s pricingStatus is quoted.
This example uses the PendingOperationStore from Keeping what recovery needs:
destinationAddressdefaults to the user’s own Portal address on that chain. Any other address must be on your environment’s destination allowlist for Agg; see Withdrawals.- To find the most the user can withdraw to a chain, call
quoteWithdrawable({ tokenSymbol, destinationChainId }). - A
partialwithdrawal succeeds. ReadcompletedAmountRawfor what arrived. withdrawretries creating the withdrawal itself. When that request fails with a 429, 502, 503 or 504, or gets no answer, it sends the same request again, with the samerequestId, for up to 3 attempts in all, 1 second and then 2 seconds apart. If every attempt was refused with a 4xx, such as a 429,withdrawrejects with the last error, notWithdrawalOutcomeUnknown. If any attempt failed with a 5xx or got no answer, it fails withWithdrawalOutcomeUnknown.
Any other failure leaves no withdrawal to follow, so the example removes the stored record. Before the
WITHDRAWING progress step nothing was sent, as with WithdrawalNotViable, InvalidAmount, an abort or AGG_LINK_REQUIRED. After it, the withdrawal either ended failed or every attempt to create it was refused. A record left behind would be resent with createWithdrawal, which skips the preview.
After WithdrawalOutcomeUnknown:
- With
details.withdrawal, the withdrawal was created: pollgetWithdrawal(details.withdrawal.withdrawalId). - Without it, creating the withdrawal got no definite answer: send
createWithdrawal(details.request)again, then poll it. ItsrequestIdmakes Agg return the original withdrawal instead of creating a second one. Don’t callwithdrawagain: it previews first, and the preview can refuse funds already on their way.
requestId is a UUID. When you don’t pass one, withdraw generates a new one on every call. To recover after the app restarts, pass your own and store it with the withdrawal’s parameters before calling, as the example above does. If the withdrawal may then exist, send createWithdrawal with the stored request (this requestId, the same parameters and the amount in base units as amountRaw).
Progress, cancellation and reconnecting
deposit, buy, sell, placeLimitOrder, redeemAll and withdraw take these options:
RECONNECTING, AWAITING_DEPOSIT_ADDRESSES, SENDING_DEPOSIT, DEPOSIT_SENT, QUOTING, FILLING, POLLING_ORDER, PLACING_ORDER, REDEEMING, PREVIEWING_WITHDRAWAL, WITHDRAWING and POLLING_WITHDRAWAL. Each event also carries what the helper has learned so far, such as quote, fill, order, txHash, idempotencyKey, withdrawalPreview or withdrawal.
Aborting. Before anything is sent, an aborted helper rejects with the abort reason. A request already sent is never abandoned or repeated:
- A fill or withdrawal that may exist ends in
OrderOutcomeUnknownorWithdrawalOutcomeUnknown, carrying its ids. - A deposit that has started sending still resolves with its result.
buy, sell and withdraw wait for the outcome, and deposit waits for the deposit addresses. Each takes a poll option with intervalMs and timeoutMs: poll on buy, sell and withdraw, and addressPoll on deposit. If the wait times out, buy, sell and withdraw fail with their outcome-unknown error, and deposit with DepositAddressesTimeout.
While polling, a helper reads through up to 5 transient failures in a row. Each request gives up after 120 seconds without an answer, failing with
AggNoResponseError.
Handling errors
Most Agg failures are one of three kinds:AggError: a request the SDK refused to send, or a helper outcome. Branch onreasonwithAggError.is(error, reason).detailsholds the context of each reason.- A failed request: the Portal API answered with an error. Read it with
AggApiError.from(error), which gives the HTTPstatus, Portal’sid, themessage, Agg’scodeandfieldswhen Agg declined the request, and thetraceIdto quote to Portal support. It also unwraps the cause of anOrderOutcomeUnknownorWithdrawalOutcomeUnknown. AggNoResponseError: the Portal API sent no usable answer, so the request may or may not have been processed. It carries atraceId. Check for it before callingAggApiError.from, which also accepts it but returns only thetraceId.
PortalIdempotencyError for an idempotencyKey Portal can’t use, a credential that couldn’t be resolved, and a rejected signature approval in connect. AggApiError.from returns undefined for all of them. A signing failure in the Portal iframe, such as an MPC error or a policy rejection, also passes through as a PortalMpcError or PortalPolicyError, and AggApiError.from wraps it like a failed request.
AggErrorId holds the ids Portal returns for Agg requests:
When Agg declines a request, the error has no
id, Agg’s HTTP status, and a message starting with Agg rejected the request. A 403 on a trading route usually means the user’s location is blocked. AggApiError.from returns undefined for a value that isn’t a failed Agg request, such as a credential failure.
The AggError reasons that come before anything is sent are NoAddress, MissingRpcUrl, AddressMismatch, EmptyIdentifier (a blank id that would reach a different route) and InvalidAmount (an amount, price or size that isn’t positive, has too many decimals, or a price of 1 or more), plus the deposit, trade and withdrawal reasons described above.
Low-level APIs
Each Portal API route, except self-custody signature submission (POST /orders/{quoteId}/signatures), has a route method that resolves with its response as { data }. A failed request rejects with the Portal API error, which you read with AggApiError.from, or with AggNoResponseError. See the endpoint reference for each route.
createLimitOrder takes the price and size as integers scaled by 1e6, which placeLimitOrder does for you. createDirectOrder places a market order on one venue without a quote; its externalId must be unique per app and at most 36 characters, and a replay is refused with a 409 rather than trading twice.
Limitations
- No self-custody fills. The SDK fills from the user’s Agg balance. Pricing and filling against the user’s own wallet (Self-custody fills) isn’t available in the Web SDK.
- Webhooks go directly from Agg to your backend; see Webhooks.
Next Steps
- Read the Agg integration page for setup, geo restrictions and compliance.
- Use idempotency keys to retry deposits safely.
- Learn about signature approvals for the
connectsignature.