# Polymarket Protocol V2: Migration Brief for Coding Agents

This file is written for an AI coding agent (Claude Code, Cursor, Codex, or similar) that maintains a Polymarket trading bot. Give it to your agent and ask it to carry out the tasks below against your codebase.

Suggested prompt for the agent:

```text
Read protocol-v2-agent-brief.md. Audit this repository against every task in it.
For each task, report whether the code already complies, then make the changes needed.
Do not change behaviour for v1 markets. Do not invent contract addresses or versions
that are not in the brief. Stop and ask before sending any on-chain transaction.
```

Source: the PR&R guide at https://polyresearchrobotics.com/guide/protocol-v2-goes-live and Polymarket's documentation at https://docs.polymarket.com. The code samples are adapted from Polymarket's docs and were not tested against a live V2 market. Verify on a small Phase 1 market before trading size.

## What Changes

Polymarket starts rolling out Protocol V2 on November 23, 2026. Protocol V2 is a new set of contracts and position tokens for new markets only. Existing markets keep their current Conditional Token Framework (CTF) contracts for trading, settlement, and redemption. Nothing is converted. A bot must handle both systems at once, often on the same account.

Protocol V2 is not CLOB V2. CLOB V2 shipped on April 28, 2026. It introduced pUSD as collateral, the CTFExchangeV2 order format, and bumped the EIP-712 Exchange domain version from `'1'` to `'2'`. Protocol V2 builds on top of it and bumps the domain version to `'3'` for new markets. If the bot is not yet on CLOB V2, finish that first. Everything below assumes pUSD collateral and domain version `'2'` as the starting point.

## Reference Facts

All contracts are on Polygon mainnet, chain ID 137.

| Item | Value |
| --- | --- |
| ExchangeV3 (V2 order matching) | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` |
| PositionManager (holds V2 positions, ERC-1155) | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` |
| Router (split, merge, redeem for V2) | `0x12121212006e4CD160D18e3f00711DA5c3372600` |
| pUSD (collateral) | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` |
| EIP-712 Exchange domain version, V2 markets | `'3'` |
| EIP-712 Exchange domain version, CTF markets | `'2'` |
| ClobAuth domain version | `'1'` (unchanged at both upgrades) |
| Gamma market field that selects the system | `version`, either `"v1"` or `"v2"` |
| Trading IDs on a v2 market | `positionIds`, an array of decimal strings |
| Trading IDs on a v1 market | `clobTokenIds`, a JSON-encoded string you must parse |
| Official SDK minimum | `polymarket-client` 0.12.0 (Python 3.11+) or `@polymarket/client` 0.12.0 |
| Base units for Router amounts | 6 decimals, `1_000_000` equals one pUSD or one share |

Rollout calendar. Later phases depend on the earlier ones running cleanly, so the Nov 24 and Dec 1 dates could slip.

| Phase | When | Markets |
| --- | --- | --- |
| 1 | Mon Nov 23, 2026, 8:30 AM ET (5:30 AM PT) | Crypto Up/Down, 5m and 15m: BNB, DOGE, HYPE, SOL, XRP, ZEC. Weather: NYC highest temperature, Warsaw highest temperature, Munich lowest temperature. |
| 2 | Tue Nov 24, 2026, no time published | BTC and ETH Up/Down at 5m, 15m and 4h. Other crypto. Remaining weather. Commodities and finance. Minor sports. |
| 3 | Tue Dec 1, 2026, no time published | Soccer. NFL and college football. NBA and college basketball. Tennis. Esports. Social count markets. |

Thanksgiving (Nov 26) has no scheduled cutover, so NFL and college football games that week stay on CTF. Polymarket's docs say some markets are created 24 hours before their trading date, so a V2 market object can appear in Gamma before trading opens.

## Task 1: Confirm the Bot Is on CLOB V2

Goal: establish the starting point before adding Protocol V2 support.

Do:

1. Find where the bot builds its EIP-712 signing domain. Confirm `version` is `'2'` for existing markets. A value of `'1'` means the bot is still pre-CLOB V2. Stop and migrate to CLOB V2 first.
2. Confirm the bot uses pUSD as collateral.
3. Rename any log line, config flag, or comment that says only "V2" so it says either "CLOB V2" or "Protocol V2".

```text
# Quick self-check: which migration state is your bot in?

# CLOB V2 order signature domain
{
  "name": "Polymarket CTF Exchange",
  "version": "2",          # '1' here means pre-CLOB V2 -- stop, migrate first
  "chainId": 137,
  "verifyingContract": "<CTFExchangeV2 address>"
}

# Protocol V2 order signature domain (new markets only)
{
  "name": "Polymarket CTF Exchange",
  "version": "3",          # only valid against ExchangeV3
  "chainId": 137,
  "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"
}
```

Verify: a grep for the domain version finds `'2'` on the existing path and no hardcoded `'1'`.

## Task 2: Branch on the Gamma `version` Field

Goal: pick the correct trading ID for every market, and never guess from which fields are present.

Do:

1. Find every place the bot reads `clobTokenIds`.
2. Before that read, check `market.version`. If `"v2"`, read `positionIds`, which is already an array of strings. If `"v1"`, JSON-parse `clobTokenIds`. Any other value raises an error and the market is skipped.
3. Match the target outcome label against `market.outcomes`, which uses the same index order, and take the ID at that index.
4. Keep every ID as a decimal string. Never pass it through `Number()`, `parseInt`, `int()` or `BigInt` to a float. A V2 position ID is a 256-bit integer and a JavaScript `Number` holds 53 bits.

```text
// V2 position ID bit layout (256 bits total)
// [moduleId: 8] [baseHash: 128] [arity: 16] [reserved: 64] [resolutionChain: 16] [conditionIndex: 16] [outcomeIndex: 8]

// WRONG: loses precision silently
const id = Number(market.positionIds[0]);

// RIGHT: keep it as a string everywhere
const id = market.positionIds[0]; // already a decimal string
```

```text
// TypeScript
function getAssetId(market, outcomeLabel) {
  const outcomes = market.outcomes; // string[]
  const idx = outcomes.indexOf(outcomeLabel);
  if (idx === -1) throw new Error(`Outcome '${outcomeLabel}' not found`);

  if (market.version === 'v2') {
    const ids = market.positionIds; // already string[]
    return ids[idx];
  } else if (market.version === 'v1') {
    const ids = JSON.parse(market.clobTokenIds); // decode first
    return ids[idx];
  } else {
    throw new Error(`Unknown market version: ${market.version}`);
  }
}

// Python equivalent
def get_asset_id(market, outcome_label):
    outcomes = market['outcomes']
    idx = outcomes.index(outcome_label)  # raises ValueError if missing
    if market['version'] == 'v2':
        return market['positionIds'][idx]
    elif market['version'] == 'v1':
        import json
        return json.loads(market['clobTokenIds'])[idx]
    else:
        raise ValueError(f"Unknown market version: {market['version']}")
```

Verify: the ID string contains only decimal digits with no `0x` prefix. The outcome label exists in `market.outcomes`. The version is exactly `'v1'` or `'v2'`. The `version` field is already present on current v1 markets, so this branch can be tested against live data today.

Use the asset ID (position ID or token ID) for order books (`GET https://clob.polymarket.com/book?token_id=<ASSET_ID>`), prices, limit and market orders, and WebSocket market subscriptions via `assets_ids`. Use the condition ID only for user-stream market subscriptions and market-wide order cancellation. They are not interchangeable.

## Task 3: Grant Approvals for ExchangeV3

Goal: let ExchangeV3 move the bot's pUSD and V2 positions. CTF approvals live on a different contract and do not carry over. Add the new approvals, do not remove the old ones.

Do, for a raw-API bot:

1. BUY approval: call `approve(EXCHANGE_V3, amount)` on pUSD. The amount must cover the full spend including fees.
2. SELL approval: call `setApprovalForAll(EXCHANGE_V3, true)` on PositionManager. One call covers all V2 positions.
3. Wait for both transactions to confirm.
4. Refresh the CLOB's allowance cache. On-chain confirmation alone is not enough. Use `asset_type=CONDITIONAL-V2` for V2 positions and `asset_type=COLLATERAL` for pUSD. Keep using `asset_type=CONDITIONAL` for CTF positions, which are tracked separately.

```text
# Pseudocode, Polygon mainnet (chain 137)

EXCHANGE_V3     = "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"
pUSD            = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"
POSITION_MGR   = "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"

# BUY approval: let ExchangeV3 spend your pUSD
pUSD_contract.approve(
    spender = EXCHANGE_V3,
    amount  = your_max_spend_including_fees   # e.g. uint256 max or a specific cap
)

# SELL approval: let ExchangeV3 transfer your conditional tokens
PositionManager_contract.setApprovalForAll(
    operator = EXCHANGE_V3,
    approved = True
)

# Wait for both transactions to confirm before proceeding
```

```http
# Refresh the CLOB's allowance cache for a V2 conditional token
GET https://clob.polymarket.com/balance-allowance/update

# Required L2 headers
POLY_ADDRESS
POLY_SIGNATURE
POLY_TIMESTAMP
POLY_API_KEY
POLY_PASSPHRASE

# Query parameters for a conditional V2 position
asset_type     = CONDITIONAL-V2
token_id       = <ASSET_ID>
signature_type = <SIGNATURE_TYPE>

# For pUSD collateral itself, swap asset_type
asset_type     = COLLATERAL

# Confirm the update worked
GET https://clob.polymarket.com/balance-allowance
# Look for ExchangeV3 in the 'allowances' entry
```

Do, for an SDK bot on `@polymarket/client` or `polymarket-client` 0.12.0 or later: keep the single existing `setupTradingApprovals()` (TypeScript `SecureClient`) or `setup_trading_approvals()` (Python `AsyncSecureClient`) call. Since SDK 0.8.0 it covers the CTF, V2 binary and V2 neg-risk approvals. Do not add a second approval call and do not remove the existing one. With gasless signing, the approval transaction is relayed and needs a configured Relayer or Builder API key.

```text
# Python (polymarket-client >= 0.12.0)
client.setup_trading_approvals()

// JavaScript (@polymarket/client)
await client.setupTradingApprovals()
```

Verify: `GET https://clob.polymarket.com/balance-allowance` lists ExchangeV3 in the `allowances` entry for a V2 position.

## Task 4: Sign V2 Orders with Domain Version 3

Goal: a signature built for the CTF exchange address is invalid on ExchangeV3. Sign with the domain that matches the market.

Do:

1. Keep the CTFExchangeV2 signed-order structure. The struct does not change.
2. For a v2 market, set `order.tokenId` to the position ID, the decimal string from `positionIds`.
3. Build the EIP-712 domain from the market `version`: version `'3'` and ExchangeV3 for v2, version `'2'` and the CTF exchange for v1.
4. Submit through the existing order flow.

```python
def build_eip712_domain(market_version: str) -> dict:
    if market_version == 'v2':
        return {
            'name': 'Polymarket CTF Exchange',
            'version': '3',
            'chainId': 137,
            'verifyingContract': '0xe3333700cA9d93003F00f0F71f8515005F6c00Aa'
        }
    else:  # v1 / CTF
        return {
            'name': 'Polymarket CTF Exchange',
            'version': '2',
            'chainId': 137,
            'verifyingContract': CTF_EXCHANGE_ADDRESS
        }

def sign_order(order: dict, market_version: str, private_key: str) -> str:
    domain = build_eip712_domain(market_version)
    # order.tokenId must already be set to the correct position ID
    # for v2: decimal string from positionIds
    # for v1: ERC-1155 token ID from the CTF contract
    return eip712_sign(domain, ORDER_TYPE_HASH, order, private_key)
```

Verify: a small BUY and a small SELL fill on one V2 market and on one CTF market, and balances move as expected on both.

Fill math, if the bot computes it: all arithmetic is in integer base units with no floating point. The core formula is `counterAmount = floor(makerAssetFill * takerAmount / makerAmount)`. For a BUY, `makerAssetFill` is collateral. For a SELL, it is shares. GTC and GTD BUY orders fill toward a share quantity. FOK and FAK BUY orders fill toward a collateral amount. BUY fees are added on top of collateral spend. SELL fees are deducted from proceeds. A bot that computes expected SELL proceeds without subtracting fees overestimates profit and loss.

## Task 5: Route Split, Merge, and Redeem Through the Router

Goal: V2 position operations go through the Router, not the CTF contract. The Router is a separate spender, so it needs its own approvals.

Do:

1. Grant `pUSD.approve(ROUTER, amount)` before `split`. Approve per call or set a large allowance once.
2. Grant `PositionManager.setApprovalForAll(ROUTER, true)` once at startup for `merge` and `redeem`.
3. Pass the condition ID as `bytes31`, amounts in 6-decimal base units, and a numeric `outcomeIndex` (0 for YES, 1 for NO) instead of a CTF index set.
4. Do not pre-transfer tokens. The Router pulls assets from the caller and returns outputs to the caller in one transaction.
5. Before `redeem`, call `PositionManager.getPayout(positionId, amount)`. Wrap it in try/except. A revert can mean the market is unresolved, so retry later. A return of `0` is a confirmed loss, so log it and do not redeem.

```text
// Router ABI (simplified)
split(bytes31 conditionId, uint256 amount)
merge(bytes31 conditionId, uint256 amount)
redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)

// outcomeIndex mapping (replaces CTF index sets 1 and 2)
// 0 = YES
// 1 = NO

// Amount examples
// 1_000_000  = 1 pUSD or 1 share
// 50_000_000 = 50 pUSD or 50 shares
```

```python
# Python pseudocode: safe payout check before redeem
try:
    payout = position_manager.functions.getPayout(
        position_id,
        amount_in_base_units
    ).call()
except Exception:
    # Market not yet resolved, skip and retry later
    return

if payout == 0:
    # Confirmed loss, no redemption needed
    log(f"Position {position_id} resolved as loss")
    return

# Safe to redeem
router.functions.redeem(
    condition_id,
    outcome_index,   # 0 for YES, 1 for NO
    amount_in_base_units
).transact()
```

Optional: to opt into hands-off settlement, call `PositionManager.setApprovalForAll(AUTO_REDEEMER, true)`. That approval only authorizes the AutoRedeemer to act when it runs. Track it separately from the Router approval, and take the AutoRedeemer address from Polymarket's V2 deployment docs rather than deriving it.

Verify: a redeem of a small amount such as `1_000_000` (one share) on a resolved Phase 1 market returns pUSD to the caller.

## Task 6: Upgrade or Replace the SDK

Goal: get onto an SDK that understands V2 markets.

Do:

1. If the bot uses `polymarket-client` (Python) or `@polymarket/client` (TypeScript), upgrade to 0.12.0 or later. Python needs 3.11 or higher. Version 0.12.0 added `CONDITIONAL-V2` balance reads and made split, merge, and redeem pick the protocol from the market `version`.
2. If the bot uses `py-clob-client-v2`, it is deprecated. Migrate to `polymarket-client`.
3. If the bot uses `@polymarket/clob-client-v2`, note that version 1.2.1 added automatic V3 routing for Protocol V2 markets via PR #105 and reverted it in the same release via PR #108. There is no auto-route. Pass `positionID` explicitly, or migrate to `@polymarket/client`.
4. Wherever the bot resolves the asset ID through the SDK, branch on `market.version`.

```bash
# TypeScript
npm install @polymarket/client@latest

# Python (requires Python 3.11+)
python -m pip install --upgrade "polymarket-client>=0.12.0"
```

```ts
// TypeScript
const assetId =
  market.version === ProtocolVersion.V2
    ? outcome.positionId
    : outcome.tokenId;

# Python
asset_id = (
    outcome.position_id
    if market.version == ProtocolVersion.V2
    else outcome.token_id
)
```

Verify: `requirements.txt` or `package.json` no longer lists a legacy client, or every legacy call site passes `positionID` explicitly.

## Task 7: Test on Phase 1 Before Phase 2

Goal: prove the full V2 path on the smallest slice before BTC and ETH open on Nov 24.

Do:

1. Run the Gamma polling loop from Nov 22 and queue any market whose `version` is `"v2"` without trading it until its window opens.
2. After 5:30 AM PT on Nov 23, place one small BUY and one small SELL on a Phase 1 alt-coin Up/Down market (BNB, DOGE, HYPE, SOL, XRP or ZEC).
3. Confirm fills, balances, and the allowance view on both a V2 market and a CTF market.
4. Test one small redeem on a resolved Phase 1 position.
5. Run a reconciliation pass against fill history to catch any fee drift before trading size.

## Final Checklist

- [ ] EIP-712 domain version is `'2'` on the existing path, `'3'` on the V2 path, and ClobAuth stays `'1'`.
- [ ] Every market read branches on `version` before touching `positionIds` or `clobTokenIds`.
- [ ] No V2 position ID is ever converted to a number.
- [ ] `pUSD.approve(EXCHANGE_V3, amount)` and `PositionManager.setApprovalForAll(EXCHANGE_V3, true)` are granted, then the CLOB allowance cache is refreshed with `asset_type=CONDITIONAL-V2`.
- [ ] V2 orders keep the CTFExchangeV2 struct, carry the position ID in `order.tokenId`, and are signed against ExchangeV3 with version `'3'`.
- [ ] Split, merge, and redeem for V2 go through the Router with their own approvals, `bytes31` condition IDs, 6-decimal amounts, and a numeric outcome index.
- [ ] `getPayout` is wrapped in try/except, and `0` is treated as a loss.
- [ ] SDK is `polymarket-client` or `@polymarket/client` 0.12.0 or later, with one `setupTradingApprovals()` call, and the Relayer or Builder API key is set for gasless wallets.
- [ ] A small live test on a Phase 1 market passed before Nov 24.
