Crypto-native prediction markets add five mathematical risk layers absent from traditional markets: stablecoin depeg risk (E[loss] = position × p_depeg × (1 - recovery)), gas cost optimization (C_gas = gas_units × gas_price × token_price), impermanent loss from AMM liquidity provision (IL = 2sqrt(r)/(1+r) - 1), collateral liquidation cascades, and bridge/smart-contract risk modeled as Poisson processes. An agent that ignores these risks is underestimating its true cost basis by 0.5-3% per trade.

Why This Matters for Agents

This is Layer 2 — Wallet. Every autonomous agent operating on Polymarket, Azuro, or any on-chain prediction market interacts with blockchain infrastructure before it ever places a trade. The wallet layer handles gas payments, stablecoin custody, bridge transfers, and collateral management. Each of these introduces quantifiable mathematical risks that don’t exist in traditional markets.

An agent that models only prediction accuracy and ignores wallet-layer costs will overestimate its edge. A Polymarket agent placing 50 trades per day on Polygon at $0.005 per trade spends $0.25 daily on gas — negligible. But that same agent bridging funds from Ethereum L1, holding USDC through a depeg scare, or providing AMM liquidity during a volatile resolution faces costs that can swamp its trading edge entirely. The math in this guide quantifies each risk so an agent’s Layer 4 intelligence module can incorporate true all-in costs.

Wallet infrastructure like Coinbase Agentic Wallets and Safe can enforce programmatic guardrails — maximum gas price thresholds, stablecoin concentration limits, automatic deleveraging — but only if the agent knows the math behind when to trigger them.

The Math

Stablecoin Depeg Risk

Every Polymarket position is denominated in USDC. Every USDC-denominated position carries implicit depeg risk: the nonzero probability that USDC loses its $1.00 peg.

Model the stablecoin price S(t) as a jump-diffusion process:

dS/S = mu*dt + sigma*dW + J*dN

where:
  mu     = drift (near zero for stablecoins under normal conditions)
  sigma  = volatility of small deviations (~0.001 annualized for USDC)
  dW     = Wiener process
  J      = jump size on depeg event (e.g., -0.10 for a 10% depeg)
  dN     = Poisson process with intensity lambda_depeg

For practical agent risk management, simplify to an expected loss model:

E[depeg_loss] = position_size × p_depeg × (1 - recovery_rate)

where:
  p_depeg       = probability of depeg event per holding period
  recovery_rate = fraction of value recovered after depeg (historically 0.90-0.99 for USDC)

Historical depeg events provide calibration data:

StablecoinEventMinimum PriceRecovery TimeRecovery Rate
USDCMarch 2023 (SVB)$0.878~3 days100%
USTMay 2022 (Luna)$0.006Never~0%
USDTVarious$0.946<24 hours100%
DAIMarch 2020$0.945~2 days100%

USDC’s March 2023 event — driven by $3.3B of reserves held at Silicon Valley Bank — demonstrates that even “safe” stablecoins carry tail risk. An agent holding $100,000 in Polymarket positions during that event faced a temporary 12.2% drawdown on collateral value, regardless of prediction accuracy.

The expected annualized depeg cost for a continuously held position:

Annual_depeg_cost = position × lambda_depeg × E[J] × (1 - recovery_rate) × 365

For USDC (conservative estimates):
  lambda_depeg  = 0.00001/day (one event per ~274 years)
  E[J]          = 0.05 (5% average depeg depth)
  recovery_rate = 0.95

Annual_depeg_cost = $100,000 × 0.00001 × 0.05 × 0.05 × 365 = $0.91

The cost is small in expectation but catastrophic in realization. This is a fat-tailed risk — low probability, high impact. An agent’s Kelly calculation should reduce position sizing to account for it.

Gas Cost Optimization

On-chain prediction market trades require gas. The gas cost formula:

C_gas = gas_units × gas_price × native_token_price / 1e9

where:
  gas_units          = computational cost of the transaction (fixed per operation type)
  gas_price          = current network fee in gwei (1 gwei = 1e-9 of native token)
  native_token_price = USD price of ETH, MATIC, etc.

Polymarket operates on Polygon PoS, where gas costs are 100-1000x lower than Ethereum L1:

NetworkTypical Gas PriceToken PriceCost per Trade (200k gas)
Ethereum L115-50 gwei~$2,500$7.50 - $25.00
Polygon PoS30-80 gwei~$0.50$0.003 - $0.008
Arbitrum0.1-0.5 gwei~$2,500$0.05 - $0.25
Base0.01-0.05 gwei~$2,500$0.005 - $0.025

Under EIP-1559 fee mechanics, the base fee adjusts per block:

base_fee(n+1) = base_fee(n) × (1 + 0.125 × (gas_used(n) - target) / target)

where:
  target = 15M gas on Ethereum, ~30M on Polygon
  gas_used(n) = actual gas consumed in block n

When a block is 100% full (30M gas), the next block’s base fee increases by 12.5%. When a block is empty, it decreases by 12.5%. An agent can model gas price as a mean-reverting process and time trades accordingly.

The optimal strategy: trade immediately when gas is below the 7-day moving average. Queue and batch when gas exceeds 2x the moving average. The expected savings from gas timing on Polygon are small ($0.001-$0.01 per trade) but compound over thousands of daily trades.

Batch Transaction Optimization

An agent placing N trades can batch them into a single multicall transaction:

C_batch = C_base + N × C_marginal

where:
  C_base     = fixed overhead of the multicall (~80,000 gas)
  C_marginal = per-trade gas within the batch (~120,000 gas vs ~200,000 for standalone)

The savings per trade:

savings_per_trade = C_standalone - (C_base/N + C_marginal)
                  = 200,000 - (80,000/N + 120,000)
                  = 80,000 - 80,000/N gas

At N = 5 trades: savings = 64,000 gas per trade (32% reduction). At N = 10: savings = 72,000 gas per trade (36%). Diminishing returns above N = 8-10 because the opportunity cost of waiting exceeds the marginal gas savings.

Impermanent Loss in AMM-Based Prediction Markets

Some prediction markets use Automated Market Makers (AMMs) instead of order books. When an agent provides liquidity to an AMM pool, it faces impermanent loss (IL) — value lost relative to simply holding the tokens.

For a constant product AMM (xy = k), the IL formula:

IL = 2 × sqrt(r) / (1 + r) - 1

where:
  r = price_final / price_initial (the price ratio)

In a prediction market context, the “price” is the YES token price (probability). If an agent provides liquidity when YES = $0.50 and the market resolves to YES = $1.00:

r = 1.00 / 0.50 = 2.0
IL = 2 × sqrt(2) / (1 + 2) - 1
IL = 2 × 1.414 / 3 - 1
IL = 0.943 - 1
IL = -0.057 = -5.7%

The IL increases dramatically as the price moves further from the initial ratio:

Price Move (YES)      r        IL
$0.50 → $0.60       1.20     -0.08%
$0.50 → $0.70       1.40     -0.53%
$0.50 → $0.80       1.60     -1.39%
$0.50 → $0.90       1.80     -2.63%
$0.50 → $0.95       1.90     -3.19%
$0.50 → $1.00       2.00     -5.72%
$0.50 → $0.10       0.20     -11.80%

Key insight: prediction markets are designed to resolve at extreme prices ($0 or $1). IL is not a bug — it’s the guaranteed cost of providing liquidity. The LP must earn enough in fees to compensate.

Liquidity Provision Yield

The expected return from market making in a prediction market AMM:

E[return_LP] = spread_capture + fee_income - IL - adverse_selection - gas_costs

where:
  spread_capture    = profit from bid-ask spread on uninformed trades
  fee_income        = protocol fee share (typically 0.1-0.3% per swap)
  IL                = impermanent loss (derived above)
  adverse_selection = losses from trading against informed participants
  gas_costs         = rebalancing and position management costs

The adverse selection component is critical. In prediction markets, informed traders (those with genuine information about the event) impose costs on liquidity providers. The Glosten-Milgrom model gives:

adverse_selection = alpha × E[|true_price - market_price|]

where:
  alpha = fraction of informed traders (typically 0.10-0.30 in prediction markets)

For an agent evaluating whether to provide liquidity, the decision criterion: provide liquidity only when expected fee income > IL + adverse_selection. Markets with high volume and low information asymmetry (e.g., highly publicized political elections) are better LP targets than niche markets where a few insiders dominate.

Collateralization and Liquidation Math

Leveraged prediction market positions (available on some DeFi protocols) require collateral. The margin math:

equity = collateral + unrealized_PnL
maintenance_margin = position_size × margin_ratio
liquidation_price = entry_price - (collateral - maintenance_margin) / position_size  [for longs]

For a 5x leveraged YES position at $0.60 with $1,000 collateral and 5% maintenance margin:

position_size = $1,000 × 5 = $5,000 (buying 8,333 YES contracts)
maintenance_margin = $5,000 × 0.05 = $250
max_loss_before_liquidation = $1,000 - $250 = $750
liquidation_price = $0.60 - $750 / 8,333 = $0.60 - $0.09 = $0.51

A 15% drop in the YES price (from $0.60 to $0.51) wipes out the position.

Liquidation Cascade Dynamics

When multiple leveraged positions are liquidated simultaneously, a feedback loop emerges:

Step 1: Price drops below liquidation threshold for agent group A
Step 2: Protocol force-sells A's positions at market price
Step 3: Force-sells push price lower
Step 4: Price now below liquidation threshold for agent group B
Step 5: Protocol force-sells B's positions
Step 6: Repeat until no more liquidatable positions exist or price hits zero

The cascade depth depends on three factors:

cascade_severity = f(leverage_concentration, orderbook_depth, correlation)

where:
  leverage_concentration = how many positions are clustered near the same liquidation price
  orderbook_depth        = available buy liquidity to absorb forced sells
  correlation            = degree to which agents use similar strategies and entry points

Model the price impact of a liquidation event:

delta_price = -volume_liquidated / (orderbook_depth × resilience_factor)

where:
  resilience_factor = market's ability to absorb sudden selling (typically 0.3-0.8)

A $500,000 liquidation event hitting an orderbook with $200,000 of buy liquidity and resilience factor 0.5 pushes the price down by:

delta_price = -$500,000 / ($200,000 × 0.5) = -5.0 (capped at available range)

This creates a temporary price dislocation — which is itself an opportunity for well-capitalized agents with no leverage. The drawdown math guide covers how to size these dip-buying strategies.

Bridge Risk Quantification

Moving funds between chains (e.g., Ethereum to Polygon for Polymarket) introduces bridge risk. Model it as:

E[bridge_loss] = amount × p_exploit × (1 - recovery_rate) + bridge_fee + gas_costs_both_sides

where:
  p_exploit     = probability of bridge exploit per transfer (Poisson process)
  recovery_rate = historical recovery from bridge hacks (~0.20-0.60)
  bridge_fee    = protocol fee (typically 0.01-0.1%)

Historical bridge exploits for calibration:

BridgeDateAmount LostRecovery
RoninMarch 2022$625M~partial
WormholeFebruary 2022$326M~100% (Jump covered)
NomadAugust 2022$190M~partial
HarmonyJune 2022$100M~0%

The aggregate bridge exploit rate across all major bridges: approximately 3-5 events per year, with total value locked across bridges of ~$10-20B. This gives a rough per-dollar-per-day exploit rate:

lambda_bridge ≈ 4 events/year × $300M avg / $15B TVL / 365 ≈ 0.00022/day per dollar

For an agent bridging $10,000 to Polygon and holding for 30 days:

E[bridge_loss] = $10,000 × 0.00022 × 30 × (1 - 0.40) = $39.60

This is a meaningful risk. Agents should minimize bridge exposure by keeping funds on-chain and bridging infrequently in large batches rather than small frequent transfers.

Smart Contract Risk

Prediction market smart contracts themselves carry exploit risk, modeled as a Poisson process:

p_exploit(t) = 1 - e^(-lambda × t)

where:
  lambda = exploit rate (events per day)
  t      = time exposed (days)

For mature, audited protocols like Polymarket (operational since 2020):

lambda ≈ 0.0001/day (one event per ~27 years)
p_exploit(365 days) = 1 - e^(-0.0001 × 365) = 3.6%

For newer, unaudited prediction market protocols:

lambda ≈ 0.001/day (one event per ~2.7 years)
p_exploit(365 days) = 1 - e^(-0.001 × 365) = 30.6%

An agent’s position sizing must account for smart contract risk as a portfolio-level constraint: never allocate more than X% of total bankroll to any single protocol, where X is determined by the protocol’s risk profile.

Worked Examples

Example 1: True Cost of a Polymarket Trade

Agent places a $5,000 YES position on “Will the Fed cut rates in June 2026?” at $0.42 on Polymarket.

Direct costs:
  Entry gas (Polygon, 250k gas at 50 gwei, MATIC=$0.50):  $0.006
  Exit gas (same):                                          $0.006
  Winner fee (if correct): 2% × $5,000 × (1/0.42 - 1):    $138.10

Risk-adjusted costs (30-day hold):
  Stablecoin risk: $5,000 × 0.00001 × 0.05 × 0.05 × 30:  $0.004
  Smart contract risk: $5,000 × 0.0001 × 30 × 0.50:       $0.75
  Bridge risk (if bridging): $5,000 × 0.00022 × 30 × 0.60: $19.80

Total all-in cost (no bridge, winning trade):               ~$138.87
Total all-in cost (with bridge, winning trade):             ~$158.67

The winner fee dominates. But for an agent that bridges frequently or operates on less-established protocols, risk-adjusted costs become material.

Example 2: LP Yield on a Polymarket-Style AMM Pool

Agent provides $10,000 of liquidity to a prediction market AMM pool at YES = $0.50, with 0.2% swap fee and 1,000 swaps expected over 30 days with $500 average size.

Fee income:
  Total volume = 1,000 × $500 = $500,000
  LP share of fees = $500,000 × 0.002 × ($10,000 / $200,000 pool) = $50.00

Impermanent loss (market resolves YES = $0.85):
  r = 0.85 / 0.50 = 1.70
  IL = 2 × sqrt(1.70) / (1 + 1.70) - 1 = 2 × 1.304 / 2.70 - 1 = -0.034 = -3.4%
  IL dollar loss = $10,000 × 0.034 = $340.00

Adverse selection (assume alpha = 0.15):
  E[|true - market|] ≈ $0.35 (from $0.50 to $0.85)
  adverse_selection_cost ≈ 0.15 × $0.35 × $500,000 × ($10,000/$200,000) = $131.25

Net return = $50.00 - $340.00 - $131.25 = -$421.25 (-4.2%)

This is why naive liquidity provision in prediction markets is a losing strategy. The IL from resolution combined with adverse selection overwhelms fee income. Only agents with superior information about the resolution timing and direction should provide LP.

Example 3: Gas Optimization via Batching on Polygon

Agent needs to place 6 trades across different Polymarket markets. Compare individual vs. batched execution:

Individual execution:
  6 × 200,000 gas = 1,200,000 gas
  At 50 gwei, MATIC=$0.50: 1,200,000 × 50 × 0.50 / 1e9 = $0.030

Batched multicall:
  80,000 (base) + 6 × 120,000 (marginal) = 800,000 gas
  At 50 gwei, MATIC=$0.50: 800,000 × 50 × 0.50 / 1e9 = $0.020

Savings: $0.010 per batch (33%)
Annual savings at 10 batches/day: $36.50

On Polygon, the absolute gas savings are trivial. Batching matters more for execution speed (one confirmation vs. six) and for reducing the window of exposure to price movement between trades.

Implementation

import numpy as np
from dataclasses import dataclass
from typing import Optional


@dataclass
class GasCostEstimate:
    """Gas cost breakdown for an on-chain prediction market trade."""
    gas_units: int
    gas_price_gwei: float
    native_token_price: float
    cost_usd: float
    network: str


@dataclass
class StablecoinRisk:
    """Quantified stablecoin depeg risk for a prediction market position."""
    position_size: float
    stablecoin: str
    daily_depeg_prob: float
    expected_depeg_depth: float
    recovery_rate: float
    holding_days: int
    expected_loss: float
    annualized_cost: float


@dataclass
class ImpermanentLossResult:
    """Impermanent loss calculation for AMM LP position."""
    initial_price: float
    final_price: float
    price_ratio: float
    il_percentage: float
    il_dollar: float
    position_size: float


def estimate_gas_cost(
    gas_units: int,
    gas_price_gwei: float,
    native_token_price: float,
    network: str = "polygon"
) -> GasCostEstimate:
    """
    Calculate gas cost in USD for an on-chain transaction.

    Args:
        gas_units: Computational gas required (e.g., 200000 for a swap)
        gas_price_gwei: Current gas price in gwei
        native_token_price: USD price of the network's native token
        network: Network name for labeling

    Returns:
        GasCostEstimate with cost breakdown
    """
    cost_usd = gas_units * gas_price_gwei * native_token_price / 1e9
    return GasCostEstimate(
        gas_units=gas_units,
        gas_price_gwei=gas_price_gwei,
        native_token_price=native_token_price,
        cost_usd=cost_usd,
        network=network
    )


def batch_gas_savings(
    n_trades: int,
    standalone_gas: int = 200_000,
    batch_base_gas: int = 80_000,
    batch_marginal_gas: int = 120_000,
    gas_price_gwei: float = 50.0,
    native_token_price: float = 0.50
) -> dict:
    """
    Calculate gas savings from batching multiple trades into a multicall.

    Args:
        n_trades: Number of trades to batch
        standalone_gas: Gas per individual trade
        batch_base_gas: Fixed overhead of multicall contract
        batch_marginal_gas: Per-trade gas within the batch
        gas_price_gwei: Current gas price in gwei
        native_token_price: USD price of native token

    Returns:
        Dict with individual cost, batch cost, savings, and percentage saved
    """
    individual_total = n_trades * standalone_gas
    batch_total = batch_base_gas + n_trades * batch_marginal_gas

    to_usd = lambda gas: gas * gas_price_gwei * native_token_price / 1e9

    return {
        "n_trades": n_trades,
        "individual_gas": individual_total,
        "batch_gas": batch_total,
        "gas_saved": individual_total - batch_total,
        "individual_cost_usd": to_usd(individual_total),
        "batch_cost_usd": to_usd(batch_total),
        "savings_usd": to_usd(individual_total - batch_total),
        "savings_pct": (1 - batch_total / individual_total) * 100
    }


def stablecoin_depeg_risk(
    position_size: float,
    holding_days: int,
    stablecoin: str = "USDC",
    daily_depeg_prob: Optional[float] = None,
    expected_depeg_depth: Optional[float] = None,
    recovery_rate: Optional[float] = None
) -> StablecoinRisk:
    """
    Quantify expected loss from stablecoin depeg risk.

    Args:
        position_size: USD value of the prediction market position
        holding_days: Expected holding period in days
        stablecoin: "USDC", "USDT", or "DAI"
        daily_depeg_prob: Override default depeg probability
        expected_depeg_depth: Override default depeg depth
        recovery_rate: Override default recovery rate

    Returns:
        StablecoinRisk with expected loss and annualized cost
    """
    defaults = {
        "USDC": (0.00001, 0.05, 0.95),
        "USDT": (0.00003, 0.04, 0.90),
        "DAI":  (0.00002, 0.03, 0.95),
    }

    d_prob, d_depth, d_recovery = defaults.get(stablecoin, (0.00005, 0.10, 0.80))

    p = daily_depeg_prob if daily_depeg_prob is not None else d_prob
    depth = expected_depeg_depth if expected_depeg_depth is not None else d_depth
    rec = recovery_rate if recovery_rate is not None else d_recovery

    expected_loss = position_size * p * depth * (1 - rec) * holding_days
    annualized = position_size * p * depth * (1 - rec) * 365

    return StablecoinRisk(
        position_size=position_size,
        stablecoin=stablecoin,
        daily_depeg_prob=p,
        expected_depeg_depth=depth,
        recovery_rate=rec,
        holding_days=holding_days,
        expected_loss=expected_loss,
        annualized_cost=annualized
    )


def impermanent_loss(
    initial_price: float,
    final_price: float,
    position_size: float
) -> ImpermanentLossResult:
    """
    Calculate impermanent loss for a constant-product AMM LP position.

    Uses the standard IL formula: IL = 2*sqrt(r)/(1+r) - 1
    where r = final_price / initial_price.

    Args:
        initial_price: YES token price when LP entered (0 to 1)
        final_price: YES token price at exit/resolution (0 to 1)
        position_size: USD value of LP position

    Returns:
        ImpermanentLossResult with IL percentage and dollar amount
    """
    r = final_price / initial_price
    il_pct = 2 * np.sqrt(r) / (1 + r) - 1
    il_dollar = position_size * il_pct

    return ImpermanentLossResult(
        initial_price=initial_price,
        final_price=final_price,
        price_ratio=r,
        il_percentage=il_pct,
        il_dollar=il_dollar,
        position_size=position_size
    )


def liquidation_price(
    entry_price: float,
    collateral: float,
    leverage: float,
    maintenance_margin_ratio: float = 0.05,
    direction: str = "long"
) -> dict:
    """
    Calculate the liquidation price for a leveraged prediction market position.

    Args:
        entry_price: Entry price of the YES contract (0 to 1)
        collateral: USD collateral posted
        leverage: Leverage multiple (e.g., 5 for 5x)
        maintenance_margin_ratio: Minimum equity ratio before liquidation
        direction: "long" or "short"

    Returns:
        Dict with position details and liquidation price
    """
    position_size = collateral * leverage
    n_contracts = position_size / entry_price
    maintenance_margin = position_size * maintenance_margin_ratio
    max_loss = collateral - maintenance_margin

    if direction == "long":
        liq_price = entry_price - max_loss / n_contracts
    else:
        liq_price = entry_price + max_loss / n_contracts

    liq_price = np.clip(liq_price, 0.0, 1.0)

    return {
        "entry_price": entry_price,
        "collateral": collateral,
        "leverage": leverage,
        "position_size": position_size,
        "n_contracts": n_contracts,
        "maintenance_margin": maintenance_margin,
        "max_loss_before_liquidation": max_loss,
        "liquidation_price": liq_price,
        "distance_to_liquidation": abs(entry_price - liq_price),
        "distance_pct": abs(entry_price - liq_price) / entry_price * 100
    }


def smart_contract_risk(
    position_size: float,
    holding_days: int,
    lambda_exploit: float = 0.0001,
    expected_loss_fraction: float = 0.50
) -> dict:
    """
    Model smart contract exploit risk as a Poisson process.

    Args:
        position_size: USD value exposed to the smart contract
        holding_days: Duration of exposure in days
        lambda_exploit: Daily exploit rate (events per day)
        expected_loss_fraction: Expected fraction of position lost in exploit

    Returns:
        Dict with exploit probability and expected loss
    """
    p_exploit = 1 - np.exp(-lambda_exploit * holding_days)
    expected_loss = position_size * p_exploit * expected_loss_fraction

    return {
        "position_size": position_size,
        "holding_days": holding_days,
        "lambda_exploit": lambda_exploit,
        "p_exploit": p_exploit,
        "p_exploit_pct": p_exploit * 100,
        "expected_loss": expected_loss,
        "annualized_p_exploit": 1 - np.exp(-lambda_exploit * 365)
    }


def total_position_cost(
    position_size: float,
    entry_price: float,
    holding_days: int = 30,
    gas_cost: float = 0.012,
    winner_fee_rate: float = 0.02,
    stablecoin: str = "USDC",
    bridge_transfer: bool = False,
    bridge_amount: Optional[float] = None,
    smart_contract_lambda: float = 0.0001
) -> dict:
    """
    Calculate the total all-in cost of a prediction market position
    including gas, fees, and risk-adjusted crypto-specific costs.

    Args:
        position_size: USD value of the position
        entry_price: YES contract entry price (0 to 1)
        holding_days: Expected holding period
        gas_cost: Total gas cost for entry + exit in USD
        winner_fee_rate: Platform fee on winnings (e.g., 0.02 for Polymarket)
        stablecoin: Stablecoin used for collateral
        bridge_transfer: Whether funds were bridged
        bridge_amount: Amount bridged (defaults to position_size)
        smart_contract_lambda: Daily exploit rate

    Returns:
        Dict with itemized costs and total
    """
    potential_profit = position_size * (1 / entry_price - 1)
    winner_fee = winner_fee_rate * potential_profit

    sc_risk = smart_contract_risk(position_size, holding_days, smart_contract_lambda)
    stable_risk = stablecoin_depeg_risk(position_size, holding_days, stablecoin)

    bridge_cost = 0.0
    if bridge_transfer:
        b_amount = bridge_amount if bridge_amount else position_size
        bridge_cost = b_amount * 0.00022 * holding_days * 0.60

    total = gas_cost + winner_fee + sc_risk["expected_loss"] + stable_risk.expected_loss + bridge_cost

    return {
        "position_size": position_size,
        "entry_price": entry_price,
        "gas_cost": gas_cost,
        "winner_fee_if_correct": winner_fee,
        "smart_contract_risk_cost": sc_risk["expected_loss"],
        "stablecoin_risk_cost": stable_risk.expected_loss,
        "bridge_risk_cost": bridge_cost,
        "total_cost_winning_trade": total,
        "cost_as_pct_of_position": total / position_size * 100,
        "breakeven_edge_required": total / position_size
    }


# --- Demo ---
if __name__ == "__main__":
    print("=== Gas Cost: Polygon vs Ethereum ===")
    polygon = estimate_gas_cost(200_000, 50.0, 0.50, "polygon")
    ethereum = estimate_gas_cost(200_000, 25.0, 2500.0, "ethereum")
    print(f"Polygon:  ${polygon.cost_usd:.4f}")
    print(f"Ethereum: ${ethereum.cost_usd:.2f}")
    print(f"Ratio:    {ethereum.cost_usd / polygon.cost_usd:.0f}x more expensive on L1\n")

    print("=== Batch Savings (6 trades on Polygon) ===")
    batch = batch_gas_savings(6)
    print(f"Individual: ${batch['individual_cost_usd']:.4f}")
    print(f"Batched:    ${batch['batch_cost_usd']:.4f}")
    print(f"Saved:      {batch['savings_pct']:.1f}%\n")

    print("=== Stablecoin Depeg Risk ($100k USDC, 30 days) ===")
    sr = stablecoin_depeg_risk(100_000, 30)
    print(f"Expected loss: ${sr.expected_loss:.4f}")
    print(f"Annualized:    ${sr.annualized_cost:.2f}\n")

    print("=== Impermanent Loss (LP at $0.50, resolves $0.85) ===")
    il = impermanent_loss(0.50, 0.85, 10_000)
    print(f"IL: {il.il_percentage:.2%} (${il.il_dollar:.2f})\n")

    print("=== Liquidation Price (5x long at $0.60) ===")
    liq = liquidation_price(0.60, 1000, 5.0)
    print(f"Liquidation at: ${liq['liquidation_price']:.4f}")
    print(f"Distance:       {liq['distance_pct']:.1f}% from entry\n")

    print("=== Total Position Cost ($5k YES at $0.42, 30 days) ===")
    tc = total_position_cost(5000, 0.42, 30, bridge_transfer=True)
    print(f"Gas:             ${tc['gas_cost']:.3f}")
    print(f"Winner fee:      ${tc['winner_fee_if_correct']:.2f}")
    print(f"SC risk:         ${tc['smart_contract_risk_cost']:.2f}")
    print(f"Stable risk:     ${tc['stablecoin_risk_cost']:.4f}")
    print(f"Bridge risk:     ${tc['bridge_risk_cost']:.2f}")
    print(f"TOTAL:           ${tc['total_cost_winning_trade']:.2f}")
    print(f"As % of position: {tc['cost_as_pct_of_position']:.2f}%")

Limitations and Edge Cases

Stablecoin risk is fat-tailed, not normally distributed. The expected loss calculation above uses a Poisson arrival rate with fixed jump size. In reality, depeg events are heterogeneous — UST’s collapse was a fundamentally different event from USDC’s SVB scare. The expected loss framework understates tail risk. An agent should supplement EV-based risk budgets with hard exposure caps: never hold more than X% of bankroll in any single stablecoin.

Gas models assume EIP-1559 mean-reversion. During extreme network congestion (NFT mints, airdrop claims, liquidation cascades), gas prices can spike 10-100x above baseline for sustained periods. An agent relying on historical gas distributions will underestimate worst-case execution costs. Priority fee auctions during congestion periods follow a first-price auction dynamic, not a mean-reverting process.

Impermanent loss formula assumes constant product AMM. Concentrated liquidity AMMs (Uniswap v3 style) have different IL profiles — concentrated positions experience amplified IL within their range. Some prediction market AMMs use custom curves (e.g., LMSR-based) where IL doesn’t apply in the same form. See the LMSR guide for AMM-specific math.

Liquidation cascade modeling is simplified. Real cascades involve multiple protocols, cross-market contagion, oracle delays, and MEV extraction by liquidation bots. The linear price impact model above underestimates cascade severity in correlated liquidation events.

Bridge risk estimates use aggregate historical data. Individual bridge risk varies dramatically based on architecture (optimistic vs. ZK vs. multisig), TVL, audit history, and bug bounty programs. The Polygon PoS bridge, which Polymarket uses, has a different risk profile than a new optimistic bridge.

Smart contract risk is protocol-specific. Polymarket’s contracts have been operational since 2020 with no exploits. Applying the same lambda to a new protocol launched last month would dramatically underestimate risk. The Poisson model also assumes a constant exploit rate, which decreases over time as contracts are battle-tested (a Bayesian update on the prior).

FAQ

How does stablecoin depeg risk affect prediction market positions?

Every prediction market position denominated in USDC or USDT carries implicit stablecoin risk. If the stablecoin depegs, your position’s dollar value drops even if your prediction is correct. The expected loss is position_size x p_depeg x (1 - recovery_rate). For USDC with an estimated daily depeg probability of ~0.001% and 95% recovery rate, the annualized drag on a $10,000 position is roughly $1.83. The risk is fat-tailed: the expected cost is tiny, but a realized depeg event (like USDC’s March 2023 episode) can cause 10%+ temporary drawdowns.

How do you calculate gas costs for prediction market trades on Polygon?

Gas cost on Polygon is C_gas = gas_units x gas_price_gwei x MATIC_price / 1e9. A typical Polymarket CLOB trade uses ~150,000-300,000 gas. At 50 gwei and MATIC at $0.50, that costs $0.004-$0.008 per trade. Compare this to Ethereum L1 where the same trade would cost $2-$15 depending on congestion. The EIP-1559 base fee adjusts by +/-12.5% per block based on utilization, creating a mean-reverting gas price that agents can time against.

What is impermanent loss in AMM-based prediction markets?

Impermanent loss occurs when the price ratio between two tokens in a liquidity pool changes from your entry ratio. For a constant product AMM, IL = 2*sqrt(price_ratio) / (1 + price_ratio) - 1. In prediction markets, this means liquidity providers lose value when the market moves decisively toward YES or NO. A move from 50% to 90% probability creates ~-3.8% IL. Since prediction markets are designed to resolve at 0 or 1, IL is a structural cost of providing liquidity, not an anomaly.

How do liquidation cascades work in leveraged prediction markets?

When a leveraged position’s equity drops below the maintenance margin, the protocol force-closes it at market price. If multiple agents are liquidated simultaneously, their forced sells push the price further down, triggering more liquidations. The cascade severity depends on leverage concentration (how many positions cluster near the same liquidation price), orderbook depth (available buy-side liquidity), and strategy correlation (whether agents entered at similar prices). Well-capitalized agents can profit from cascades by placing limit buy orders below clusters of liquidation prices.

How does an autonomous agent optimize gas costs for batch trading?

An agent batches multiple prediction market trades into a single multicall transaction, reducing per-trade gas overhead by 30-60%. The formula: savings_per_trade = standalone_gas - (batch_base / N + marginal_gas). On Polygon, the absolute dollar savings are small ($0.001-$0.01 per trade), but batching reduces execution risk by requiring only one block confirmation instead of N. The optimal batch size balances gas savings against the opportunity cost of waiting to accumulate trades — typically 3-8 trades per batch on Polygon given its 2-second block times.

What’s Next

Crypto-specific wallet-layer risks are the hidden costs that separate profitable agents from unprofitable ones. Understanding gas, stablecoin risk, and liquidation math is essential before deploying any on-chain trading strategy.

  • Wallet infrastructure: The Agent Wallet Comparison reviews how Coinbase Agentic Wallets and Safe handle gas management, stablecoin custody, and programmable risk limits.
  • AMM-specific math: The LMSR and Automated Market Maker Math guide derives the cost function and LP dynamics for Hanson’s market scoring rule — the AMM design most prediction markets use.
  • Bankroll risk management: Drawdown Math and Variance in Betting covers how to size positions accounting for the additional variance introduced by crypto-layer risks.
  • Pipeline integration: The Odds API Edge Detection Pipeline shows how to incorporate gas and fee adjustments into a live trading pipeline.
  • Sportsbook alternative: For agents that prefer fiat rails, offshore sportsbook infrastructure avoids crypto-layer complexity entirely — at the cost of higher vig and slower settlement.