Skip to main content
Portal’s Web SDK lets your users trade prediction markets on venues such as Polymarket, Kalshi and Limitless through the 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

With portal.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
The Agg integration page explains how Agg works: the managed balance, quotes and fills, and how venues settle. The API has two kinds of methods:
  • Helpers (connect, isConnected, deposit, buy, sell, placeLimitOrder, redeemAll and withdraw) 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.
Chain ids are CAIP-2, for example 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 rpcConfig entry for every chain the SDK signs or sends on: Polygon (eip155:137), where connect signs by default, and every chain you deposit from. The default rpcConfig covers the 13 built-in chains. An explicit rpcConfig replaces the defaults rather than extending them. Without an entry, the helper fails with MissingRpcUrl and nothing is signed or sent.
Linking and trading require a Portal client without account abstraction. Agg signs users in with the wallet’s own key, so the Portal API refuses everything except discovery and market data for an account-abstracted client with AGG_ACCOUNT_ABSTRACTION_UNSUPPORTED. isConnected(), getLink() and deleteLink() reject with it too instead of reporting the client as unlinked. Discovery and market data still work.
Live trading is geo-restricted. Every venue blocks some countries, and the United States is blocked on all of them. Geofencing is your responsibility: read Geo restrictions and Compliance before you ship. Pass mode: 'paper' to simulate trades from any country while you build; confirm with Snag that paper trading is enabled for your Agg app first.
The examples in this guide use an 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 by venueMarketOutcomes[].id on its market.
Lists are paginated: pass 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.
Nothing is signed unless the chain has an RPC URL configured and the sign-in message names the wallet’s own address (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) and getOrderbooks(venueMarketIds) return live prices and books for a batch of markets. Each order book entry’s requestedMarket carries the sizeStepRaw and minSizeRaw a limit order must respect.
  • getOutcomeOrderbook(outcomeId) returns one outcome’s ladder and depth.
  • getChartBars returns OHLCV bars for one outcome. getChartHistoryManifest returns 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.
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.
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 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:
  • UnsupportedDepositToken when Agg doesn’t take the token on that chain
  • AmbiguousDepositToken when the symbol matches several tokens
  • DepositAddressesTimeout when the deposit addresses aren’t ready in time
  • MissingRpcUrl when chainId has no RPC URL configured
  • InvalidAmount when amount isn’t positive or has more decimals than the token, not counting trailing zeros
An 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.
  1. 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.
  2. To retry, call deposit again with details.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’s cause, recognized by isIdempotencyRejection. See Handle a rejection for what each refusal means.
  3. Use a new key only once you’ve confirmed the first transfer didn’t land and can no longer land.
When you don’t pass idempotencyKey, deposit generates a new key on every call, so calling it again without the key from the error sends a second transfer. A retry with the same key can also be refused with IDEMPOTENCY_KEY_REUSED, because deposit rebuilds the transfer on every call. This happens most often on Solana, and when Agg has issued a new deposit address.

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.
  • price is USD per share, below 1, with at most 6 decimals, not counting trailing zeros. shares also takes at most 6 decimals, not counting trailing zeros. Size orders in multiples of the market’s sizeStepRaw and at least its minSizeRaw, which getOrderbooks returns.
  • timeInForce defaults to GTC. expiresAt is required with GTD.
  • listOrders({ orderType: 'limit' }) lists the user’s limit orders. Cancel an open one by its id.
A failure without a definite answer may still have placed the order. Check listOrders before placing it again.
Polymarket’s $1 minimum for orders that trade at once (price × shares) is applied after submission: placeLimitOrder resolves, and the order later fails, with the reason in errorMessage on listOrders. Check price × shares before submitting.

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:
  • destinationAddress defaults 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 partial withdrawal succeeds. Read completedAmountRaw for what arrived.
  • withdraw retries 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 same requestId, 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, withdraw rejects with the last error, not WithdrawalOutcomeUnknown. If any attempt failed with a 5xx or got no answer, it fails with WithdrawalOutcomeUnknown.
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: poll getWithdrawal(details.withdrawal.withdrawalId).
  • Without it, creating the withdrawal got no definite answer: send createWithdrawal(details.request) again, then poll it. Its requestId makes Agg return the original withdrawal instead of creating a second one. Don’t call withdraw again: 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).
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 reconnecting

deposit, buy, sell, placeLimitOrder, redeemAll and withdraw take these options:
The steps are 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 OrderOutcomeUnknown or WithdrawalOutcomeUnknown, carrying its ids.
  • A deposit that has started sending still resolves with its result.
Waiting. 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 on reason with AggError.is(error, reason). details holds the context of each reason.
  • A failed request: the Portal API answered with an error. Read it with AggApiError.from(error), which gives the HTTP status, Portal’s id, the message, Agg’s code and fields when Agg declined the request, and the traceId to quote to Portal support. It also unwraps the cause of an OrderOutcomeUnknown or WithdrawalOutcomeUnknown.
  • AggNoResponseError: the Portal API sent no usable answer, so the request may or may not have been processed. It carries a traceId. Check for it before calling AggApiError.from, which also accepts it but returns only the traceId.
Other errors pass through unchanged: the signal’s abort reason, a 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