Polymarket smart contracts on Polygon settle matched orders, track conditional outcome tokens, and let holders redeem positions after payout values are recorded. The offchain order book handles order submission and matching, so Polygon logs show settlement rather than a complete history of the book. This guide maps the contracts, then walks through a read-only verification of one Exchange V2 transaction and a bounded log query you can use to test an indexer.
The boundary between order matching and settlement
Polymarket uses an offchain central limit order book (CLOB) and onchain settlement. Traders sign orders, the offchain system matches them, and an operator submits matches to the exchange contract. A signed order is not itself a Polygon transaction, and an order-book update is not proof of settlement. For that, inspect a successful transaction receipt and decode the relevant exchange events.
Choose the data source by what you need to prove. Use the CLOB for book depth and available quotes, market metadata for the question and its outcome labels, and Polygon RPC for recorded fills, transfers, and payout state. An RPC-only indexer cannot reconstruct orders that never settled onchain. Conversely, a market data feed is not a substitute for a receipt when reconciling an actual transfer.
Exchange V2 contracts and deployment references
The official CTF Exchange V2 repository lists two exchange deployments for Polygon: CTFExchangeV2 at 0xE111180000d2663C0091e4f400237545B87B996B and NegRiskCtfExchangeV2 at 0xe2222d279d744050d28e00520010520000310F59. The repository also lists a wrapped collateral token, its proxy and implementation, and contracts for collateral handling. An exchange address, token proxy, and collateral adapter serve different purposes; they are not interchangeable filters for fills.
Treat these as versioned reference addresses, not a promise about every historical trade. Before decoding, record the chain ID, emitting address, deployment block range, and ABI revision. Check the official deployment table and verified explorer source for the transaction's era. Polygon mainnet and Amoy are different chains even where deployment addresses look identical. A historical exchange audit is useful only within its stated scope; match each audit to the code revision and contracts it actually covers.
Conditional tokens, collateral, and market resolution
The Conditional Token Framework represents positions as ERC-1155 tokens. A condition identifies a specific oracle, question identifier, and number of outcome slots. A position ID identifies a collateral-backed outcome collection; it is not the condition ID or the market's human-readable slug. Map each token ID to its outcome using market metadata and verify that mapping before labeling transfers. Store token IDs as integers with arbitrary precision or as strings, not JavaScript Number values.
In a simple binary market, splitting collateral creates a complete set of YES and NO positions, and merging equal quantities of both returns collateral. Neither operation requires the market to have resolved. After resolution, redemption uses the reported payout vector: in an ordinary winner-takes-all result, the winning position redeems for its collateral share and the losing position pays zero. Read the recorded payout values rather than inferring them from token prices or the market's closing time.
Polymarket uses UMA's optimistic oracle for resolution. A proposed answer can be disputed, so the event ending, a result being proposed, and the condition becoming redeemable are separate steps. Negative-risk markets also link outcomes across a group of mutually exclusive markets. Where exactly one outcome can win, a NO position on one outcome is economically equivalent to YES positions on the others, and the negative-risk machinery supports that conversion. Check the market's configuration and adapter before applying standalone binary accounting.
Inputs for a read-only Polygon verification
Select a transaction hash from an actual exchange settlement on Polygon mainnet. Confirm the market uses the standard or negative-risk exchange, and obtain the event ABI for that deployment. For the examples, use Bash, curl, jq, Python 3, and a Polygon RPC endpoint that serves transaction receipts and logs. No wallet, private key, token approval, or write access is needed.
The first example requires RPC_URL, TX_HASH, and EXCHANGE_ADDRESS. It checks chain ID 137 (0x89), requires a successful receipt, and lists only logs emitted by the exchange you selected. Keep the RPC URL out of shared terminal output if it contains credentials. Use the network directory and RPC API service overview when checking infrastructure options against your chain and method requirements.
Receipt verification and fill identification
Run this in a clean working directory after setting the three environment variables. It saves the full receipt as receipt.json so you can inspect related token or adapter logs without refetching it. A nonempty exchange-log array is the first check, not the final proof of a fill.
- Match
topics[0]to a non-anonymous fill event in the verified ABI, then decode its indexed fields from topics and its other fields fromdata. Record the log index of the fill you verified. - Cross-check the decoded assets and amounts against the market's outcome IDs and the collateral token's decimals. Review token transfer logs in the same receipt if you need to explain the balance changes.
- Do not count all exchange logs as fills or expect exactly one fill per transaction. A settlement transaction can emit several events, and token movements can include transfers, mints, or burns.
set -euo pipefail
: "${RPC_URL:?Set RPC_URL}" "${TX_HASH:?Set TX_HASH}" "${EXCHANGE_ADDRESS:?Set EXCHANGE_ADDRESS}"
rpc() {
jq -nc --arg method "$1" --argjson params "$2" \
'{jsonrpc:"2.0",id:1,method:$method,params:$params}' |
curl -fsS --max-time 30 -H 'Content-Type: application/json' --data-binary @- "$RPC_URL" |
jq -e 'if .error then error(.error | tostring) else .result end'
}
chain_id=$(rpc eth_chainId '[]' | jq -r '.')
[[ "$chain_id" == '0x89' ]] || { echo "Expected Polygon mainnet; got $chain_id" >&2; exit 1; }
receipt=$(rpc eth_getTransactionReceipt "$(jq -nc --arg hash "$TX_HASH" '[$hash]')")
jq -e '.status == "0x1"' <<< "$receipt" >/dev/null
printf '%s\n' "$receipt" > receipt.json
jq -e --arg exchange "$EXCHANGE_ADDRESS" '
[.logs[] | select((.address | ascii_downcase) == ($exchange | ascii_downcase))
| {address, blockNumber, blockHash, transactionHash, logIndex, topics, data}]
| if length > 0 then . else error("No logs from selected exchange") end
' receipt.jsonBlock-scoped log retrieval and backfill validation
Start with the receipt's block before scanning a range. Set LOG_INDEX to the hex log index of the fill you decoded and make RPC_URL, EXCHANGE_ADDRESS, and LOG_INDEX available to the Python process. The script takes the event topic from that verified log and queries by block hash, exchange address, and topic. It should find the exact original log even if other fills share the same block. If the endpoint does not accept a blockHash filter, use the receipt's block number for both bounds and check returned block hashes against the receipt.
For a historical backfill, replace blockHash with inclusive fromBlock and toBlock bounds and keep the exchange and event topic fixed. Use a fixed interval that includes the anchor block and falls within the version's deployment period. Run the same interval as one query if allowed, then as smaller, nonoverlapping windows. Compare complete log identity sets, not just counts. The single-block test covers one event signature; repeat it for any additional fill events or deployments your indexer needs.
python3 - <<'PY'
import json
import os
from urllib.request import Request, urlopen
with open('receipt.json') as f:
receipt = json.load(f)
address = os.environ['EXCHANGE_ADDRESS'].lower()
index = int(os.environ['LOG_INDEX'], 16)
anchor = next((log for log in receipt['logs']
if log['address'].lower() == address
and int(log['logIndex'], 16) == index), None)
if not anchor or not anchor['topics']:
raise SystemExit('Select a decoded exchange fill log from the receipt')
params = [{'blockHash': receipt['blockHash'], 'address': address,
'topics': [anchor['topics'][0]]}]
request = Request(os.environ['RPC_URL'],
data=json.dumps({'jsonrpc': '2.0', 'id': 1,
'method': 'eth_getLogs', 'params': params}).encode(),
headers={'Content-Type': 'application/json'})
with urlopen(request, timeout=30) as response:
payload = json.load(response)
if 'error' in payload:
raise SystemExit(payload['error'])
logs = payload['result']
if not any(log['blockHash'] == receipt['blockHash']
and log['transactionHash'] == receipt['transactionHash']
and int(log['logIndex'], 16) == index for log in logs):
raise SystemExit('The receipt log was not returned by eth_getLogs')
print(f'Verified anchor fill; matching event logs in block: {len(logs)}')
PYReproducible backfill results
Fill in the table from your own runs. Record the inclusive bounds, exchange address, topic, and endpoint configuration alongside it. Compare (blockHash, transactionHash, logIndex) sets on the same chain. If a range fails, record the error rather than treating it as an empty result. Keep the interval well behind the head so chain movement is less likely to distort the comparison.
| Test | RPC calls and retries | Unique matching logs | Verification |
|---|---|---|---|
| Receipt block by hash | Record totals | Record count | Anchor present or missing |
| Fixed interval, single query | Record totals or error | Record count if successful | Baseline identity set |
| Same interval, smaller windows | Record totals | Record count | Compare identity sets and list differences |
If you measure elapsed time, repeat each configuration from the same client location with the same interval and concurrency. Report request errors alongside timing; a fast partial backfill is not a throughput win. Use published RPC plans and pricing for cost assumptions, and compare dedicated node options only if your measured workload justifies evaluating them.
Failure modes and interpretation limits
A null receipt can mean the transaction is pending or the hash belongs to another chain. A successful receipt with no logs from your selected exchange may be a token operation rather than a fill, or you may have filtered for the wrong version or negative-risk deployment. Inspect every emitting address before changing the filter. The top-level to address does not tell you which contracts emitted logs through internal calls.
If a fill appears in the receipt but not in a range scan, first check the topic, emitter, and inclusive bounds. Then repeat the single-block query and verify the canonical block hash at that height, especially near the head. For timeouts or range limits, split the range; for throttling, back off and retry. Do not advance a durable checkpoint until every window through that block has completed. Near the head, retain block hashes and roll back orphaned logs if the chain reorganizes.
Keep market labels, wallet identities, and trade counts separate from raw event facts. A signer, a smart contract wallet holding assets, and the operator submitting settlement need not be the same address. Likewise, fill count, transaction count, and token transfer count answer different questions. Decide which one your application reports before comparing it with an API or dashboard.
Production indexing and reconciliation
Keep a versioned registry keyed by chain, contract address, and active block range. Before streaming new blocks, save a known receipt for each exchange path you support and turn it into a regression test for event decoding and market attribution. Add separate fixtures for splitting, merging, and redemption if you track balances; a fills-only index will miss those changes.
Start with settled trades for one market. Reconcile its fill logs first, then add market metadata for labels and payout state for redemption. If you need live quotes or unfilled orders, add the CLOB feed rather than stretching the onchain index beyond what it records. For more guidance on the infrastructure side, return to OnFinality Learn.