polygolem

module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 11, 2026 License: MIT

README

polygolem

CI Go Version Latest Release

Production-safe Polymarket infrastructure for the deposit-wallet era.

A single Go binary and SDK for trading on Polymarket V2.

Built for Polymarket's current deposit-wallet production model — with local signing, no external SDKs, and no opaque runtime layers.

For operators who want verifiable trading infrastructure instead of opaque wrappers — validated against live Polygon mainnet flows, not mocks or paper environments.


Try It in 60 Seconds (No Credentials Needed)

All outputs below come from live Polygon mainnet responses.

git clone https://github.com/TrebuchetDynamics/polygolem
cd polygolem && go build -o polygolem ./cmd/polygolem

./polygolem health
# {"clob":"ok","gamma":"ok"}

./polygolem orderbook price --token-id 1391568931...637394586
# {"price":"0.012","token_id":"1391568931...637394586"}

./polygolem orderbook spread --token-id 1391568931...637394586
# {"spread":"0.002","token_id":"1391568931...637394586"}

./polygolem discover search --query "btc 150k" --limit 3

That's polygolem talking to live Polymarket — no key, no credentials, no sign-up. Read-only is the default for everything until you set POLYMARKET_PRIVATE_KEY.


Production Validation

Production-validated: Polygon mainnet · 2026-05-08 reference run

Every tx hash, gas figure, and pUSD movement is documented from EOA private key to filled buy + sell.

Core trading flows are production-validated today: headless relayer onboarding, deposit-wallet deploy + funding, CLOB V2 trading + cancels, advanced order types, market discovery, streaming, and local risk controls.


Why polygolem Exists

In April 2026 Polymarket migrated to V2: a new exchange, a new stablecoin (pUSD), and a new requirement that orders be placed by deposit wallets (ERC-1967 proxies that validate signatures via ERC-1271) instead of EOAs.

That broke the old assumption that an EOA is the order maker. Many existing Polymarket bots, wrappers, and unofficial SDKs still sign as EOAs; those paths can produce ghost fills that appear in the book and never settle.

polygolem only knows the production-safe path:

  • Deposit-wallet only — the current production order model (signatureType=3 / POLY_1271, validated on-chain via ERC-1271)
  • Local signing — your private key never leaves the process
  • Spec-implemented protocol — no shimmed Python or JS SDK in the trust path
  • CREATE2 wallet derivation verified against the official Polymarket Python SDK
  • Read-only by default — every authenticated command requires explicit credentials

EOA, proxy, and Gnosis Safe paths are intentionally not supported.

Why Go?

One language. One binary. No hidden runtime layers between your private key and the exchange. No transitive npm or pip dependencies that get to see your signing key.

The on-chain identity model the rest of this README is built around:

  EOA  ──signs──▶  Order
   │              (signatureType=3, maker=DepositWallet, signer=DepositWallet)
   │
   ▼ derives (CREATE2)              ▼ submitted by
 Deposit Wallet  ◀──holds pUSD──    Polymarket matching engine
 (ERC-1967 proxy,                   (gas-sponsored fillOrders settlement)
  validates signatures              ──┐
  via ERC-1271)                       │
                                      ▼
 V2 Relayer  ──sponsors──▶  WALLET-CREATE + approval batch
 (relayer-v2.polymarket.com)

The EOA signs; the deposit wallet holds funds and is the on-order maker; Polymarket-run services pay every gas fee except your single ERC-20 funding transfer. See docs/LIVE-TRADE-WALKTHROUGH.md for the full lifecycle with real txes.


What Works Today

Covered by the 2026-05-08 Polygon mainnet reference run:

Trading

  • Headless V2 relayer onboarding
  • Deposit-wallet deploy + funding
  • CLOB V2 trading + cancels
  • Advanced order types

Market Data

  • Gamma + CLOB market discovery
  • Public CLOB WebSocket market stream, including V2 custom feature events
  • Normalized live best bid, best ask, spread, midpoint, tick size, last trade, and book snapshots
  • Order book price + spread helpers

Safety

  • Read-only default CLI/SDK surface
  • Local risk controls
  • Secret redaction

Safety Model

polygolem is trading infrastructure. Trust matters more than features. The SDK defaults toward preventing irreversible mistakes.

Read-only by default Authenticated operations require an explicit private key in env.
Deposit-wallet only Cannot accidentally sign as an EOA, proxy, or Safe.
Local signing The process holds the key; no signing service in the trust path.
No external SDKs All wallet derivation, EIP-712, ERC-7739, and relayer calls are in this repo.
Pre-trade caps + daily limits + circuit breaker Configurable risk controls in internal/risk.
Secret redaction API keys and signatures are redacted in logs (internal/transport).

See docs/SAFETY.md for the full safety model.


Trade in Four Commands

export POLYMARKET_PRIVATE_KEY="0x..."

polygolem deposit-wallet onboard --fund-amount 0.71 # auth + deploy + approve + enable trading + fund
polygolem clob update-balance --asset-type collateral
polygolem clob market-order --token <ID> --side buy --amount 1 --price 0.012 --order-type FOK
# {
#   "success": true,
#   "orderID": "0x43083109...c423d793d",
#   "status": "matched",
#   "makingAmount": "1",
#   "takingAmount": "86.606666",
#   "transactionsHashes": ["0x74ad015d...4f7adc"]
# }

After onboarding, every trade is fully headless. Total user-paid cost on the reference run was ~$0.01 in POL gas for the single ERC-20 transfer that funds the deposit wallet — WALLET-CREATE, the 6-call approval batch, and every CLOB settlement are sponsored by Polymarket-run services. See the walkthrough for the per-tx breakdown.

Identity model: Polymarket login signs with the EOA. That is why polymarket.com may ask 0x33e4... to sign the SIWE message. The deposit wallet remains the trading wallet: it holds pUSD, appears as the POLY_1271 order maker/signer, receives CTF positions, and handles settlement. polygolem deposit-wallet onboard performs the SIWE/profile/relayer step automatically when no relayer key is configured. polygolem auth login is still available as an explicit refresh/inspection command. Browser setup is now fallback-only; see docs/BROWSER-SETUP.md.

After a Fill

status=matched means the CLOB filled the order. It does not mean the market won. Polygolem treats post-trade state as three separate checks:

  • matched: the order filled and shares moved into the deposit wallet.
  • winning: the market resolved in favor of the held outcome.
  • redeemable: the Data API reports the held winning position can be redeemed.

For V2 deposit wallets, redeem has one supported production path: the owner signs an EIP-712 WALLET batch, Polymarket's relayer submits it through the deposit-wallet factory, and the wallet call targets a pUSD collateral adapter. Standard markets use CtfCollateralAdapter; negative-risk markets use NegRiskCtfCollateralAdapter. Existing deposit wallets that only ran the six-call trading approval batch need a separate adapter-approval migration before their first V2 redeem.

The first-class SDK/CLI settlement surface is pkg/settlement plus deposit-wallet settlement-status, deposit-wallet redeemable, and deposit-wallet redeem. settlement-status is the read-only readiness gate: it checks wallet bytecode, relayer credentials, Data API reachability, and adapter approvals before a live bot should place more orders. The redeem commands build the V2 adapter path and fail closed on missing adapter approvals. If the relayer rejects adapter calls as not allowlisted, verify the adapter constants against Polymarket's current contracts reference first; stale adapter addresses caused the 2026-05-09 live settlement blocker. If the addresses are current, stop. The production factory does not expose a direct EOA fallback and raw ConditionalTokens redeem is not a deposit-wallet fallback. SAFE/PROXY relayer examples do not apply to deposit-wallet positions. See docs/SAFETY.md, docs/CONTRACTS.md, and docs/DEPOSIT-WALLET-REDEEM-VALIDATION.md.


Go SDK

If you'd rather embed polygolem in a larger Go service, every CLI subcommand is a thin wrapper around importable pkg/ packages:

Package What it does
pkg/universal One typed client over Gamma + CLOB + Data API + Stream + Discovery (70+ methods)
pkg/clob CLOB V2 — market data, orders, balances, builder fees
pkg/gamma Read-only Gamma market discovery (26 methods)
pkg/stream Public CLOB WebSocket market stream
pkg/marketdata Live share-price snapshots from stream events
pkg/relayer V2 Relayer client — WALLET-CREATE, batch, nonce
pkg/settlement V2 winner redemption planning, adapter calls, and readiness gates
import (
    "context"
    "fmt"

    "github.com/TrebuchetDynamics/polygolem/pkg/universal"
)

c := universal.NewClient(universal.Config{})
ctx := context.Background()

const btcYesToken = "13915689317269078219168496739008737517740566192006337297676041270492637394586"

price, _ := c.Price(ctx, btcYesToken, "buy")
spread, _ := c.Spread(ctx, btcYesToken)
fmt.Printf("BTC $150k YES — price %s, spread %s\n", price, spread)
// BTC $150k YES — price 0.012, spread 0.002

Full package boundaries, dependency direction, and internal implementation details are documented in docs/ARCHITECTURE.md.


Common Workflows

I want to... Run
Find an active market polygolem discover search --query "..."
Inspect the book polygolem clob book <token-id>
Resolve a token's CLOB market polygolem clob market-by-token <token-id>
Check my deposit wallet status polygolem deposit-wallet status
Place a limit buy polygolem clob create-order --token <ID> --side buy --price 0.5 --size 10
Place a market FOK buy polygolem clob market-order --token <ID> --side buy --amount 1 --price <slippage_cap>
Cancel everything polygolem clob cancel-all
Read my collateral balance polygolem clob balance --asset-type collateral

Full CLI reference (auto-generated, every flag and example): docs/COMMANDS.md.


Environment

  • Required for any authenticated command: POLYMARKET_PRIVATE_KEY.
  • Automatic by polygolem: V2 relayer key is minted and persisted on first wallet use; CLOB L2 keys are created or derived on demand for order auth.
  • Optional: POLYMARKET_BUILDER_CODE for V2 order attribution.

The deposit wallet address is derived locally from the private key; no API call required. Full env reference in docs/ONBOARDING.md.


Docs

Document What it covers
Live Trade Walkthrough End-to-end 2026-05-08 reference run: every tx, gas figure, and pUSD movement from EOA private key to a filled buy + sell.
Onboarding Single source of truth — complete deposit wallet flow, troubleshooting.
Headless Enable Trading SDK support for the UI ClobAuth and token-approval signing prompts.
Browser Fallback Manual signing fallback and security guidance when headless login is blocked.
Safety Risk controls, deposit-wallet-only enforcement, circuit breakers.
Contracts Contract addresses, factory ABI, CREATE2 derivation, and deployment status source-of-truth rules.
Architecture Package boundaries and dependency direction.
Commands Auto-generated CLI reference.
Deposit Wallet Migration V1→V2 survival guide for older bots.
polygolem.trebuchetdynamics.com Documentation site — searchable HTML version of the full doc tree, with landing page.

Status

v0.1.1 — production-validated against Polygon mainnet on 2026-05-11 (reference run).

Core trading flows are production-validated today.

Release signing, broader exchange abstractions, and extended automation surfaces are still hardening.

Planned: a guided read-only demo pipeline for onboarding and API graph exploration.

See CHANGELOG.md for per-version detail.

Directories

Path Synopsis
cmd
eoa_key_scout command
eoa_key_scout tests whether an EOA-owned CLOB API key can be used to place deposit-wallet (sigtype-3) orders.
eoa_key_scout tests whether an EOA-owned CLOB API key can be used to place deposit-wallet (sigtype-3) orders.
indexer_probe command
indexer_probe is a long-running diagnostic that tests whether a Polymarket backend indexer eventually registers an EOA→depositWallet relationship some time after the on-chain WALLET-CREATE.
indexer_probe is a long-running diagnostic that tests whether a Polymarket backend indexer eventually registers an EOA→depositWallet relationship some time after the on-chain WALLET-CREATE.
live_siwe_probe command
live_siwe_probe is a one-shot diagnostic that exercises the full headless onboarding pipeline against production with a throwaway EOA:
live_siwe_probe is a one-shot diagnostic that exercises the full headless onboarding pipeline against production with a throwaway EOA:
parity_erc7739 command
parity_erc7739 emits the intermediate ERC-7739 / POLY_1271 wrap-signature hashes for the canonical polydart OrderV2Draft.
parity_erc7739 emits the intermediate ERC-7739 / POLY_1271 wrap-signature hashes for the canonical polydart OrderV2Draft.
parity_walletbatch command
parity_walletbatch emits the intermediate hashes of a canonical DepositWallet.Batch typed-data sample.
parity_walletbatch emits the intermediate hashes of a canonical DepositWallet.Batch typed-data sample.
polygolem command
polygolem_docs command
internal
auth
Package auth provides Polymarket authentication primitives — L0 / L1 / L2 auth, EIP-712 signing, deposit-wallet CREATE2 derivation, and builder attribution.
Package auth provides Polymarket authentication primitives — L0 / L1 / L2 auth, EIP-712 signing, deposit-wallet CREATE2 derivation, and builder attribution.
cli
Package cli builds the polygolem Cobra command tree and wires command handlers to typed protocol, execution, and safety packages.
Package cli builds the polygolem Cobra command tree and wires command handlers to typed protocol, execution, and safety packages.
clob
Package clob is the CLOB API client — full read plus authenticated surface, EIP-712, POLY_1271, and ERC-7739 signing paths.
Package clob is the CLOB API client — full read plus authenticated surface, EIP-712, POLY_1271, and ERC-7739 signing paths.
config
Package config loads polygolem configuration via Viper — defaults, environment binding, file overrides, validation, and credential redaction.
Package config loads polygolem configuration via Viper — defaults, environment binding, file overrides, validation, and credential redaction.
dataapi
Package dataapi is the read-only Polymarket Data API client — positions, volume, trades history, and leaderboards.
Package dataapi is the read-only Polymarket Data API client — positions, volume, trades history, and leaderboards.
errors
Package errors provides structured error types and code helpers used across polygolem clients and command handlers.
Package errors provides structured error types and code helpers used across polygolem clients and command handlers.
execution
Package execution defines the executor interface and ships the paper-mode implementation.
Package execution defines the executor interface and ships the paper-mode implementation.
gamma
Package gamma is the typed Gamma HTTP client used internally by polygolem — markets, events, search, tags, series, sports, comments, and profiles.
Package gamma is the typed Gamma HTTP client used internally by polygolem — markets, events, search, tags, series, sports, comments, and profiles.
marketdiscovery
Package marketdiscovery provides high-level market discovery by joining Gamma metadata with CLOB tick-size and orderbook details.
Package marketdiscovery provides high-level market discovery by joining Gamma metadata with CLOB tick-size and orderbook details.
modes
Package modes parses and gates the polygolem operating modes — read-only, paper, and live.
Package modes parses and gates the polygolem operating modes — read-only, paper, and live.
orders
Package orders defines OrderIntent, the fluent builder, validation rules, and order lifecycle states used by both paper and live executors.
Package orders defines OrderIntent, the fluent builder, validation rules, and order lifecycle states used by both paper and live executors.
output
Package output renders command results as either tables or stable JSON envelopes and emits structured error responses.
Package output renders command results as either tables or stable JSON envelopes and emits structured error responses.
paper
Package paper holds local-only paper-trading state — positions, fills, and persisted snapshots.
Package paper holds local-only paper-trading state — positions, fills, and persisted snapshots.
polytypes
Package polytypes holds the Polymarket protocol-level types shared across CLOB, Gamma, Data API, and stream clients.
Package polytypes holds the Polymarket protocol-level types shared across CLOB, Gamma, Data API, and stream clients.
preflight
Package preflight runs local and remote readiness probes before polygolem performs any state-changing operation.
Package preflight runs local and remote readiness probes before polygolem performs any state-changing operation.
relayer
Package relayer is the builder relayer client — WALLET-CREATE, WALLET batch, nonce reads, and operation polling.
Package relayer is the builder relayer client — WALLET-CREATE, WALLET batch, nonce reads, and operation polling.
risk
Package risk provides per-trade caps, daily loss limits, and the circuit breaker that gates live order submission.
Package risk provides per-trade caps, daily loss limits, and the circuit breaker that gates live order submission.
rpc
Package rpc provides direct on-chain helpers for Polygon operations — primarily ERC-20 pUSD transfers from an EOA used by deposit-wallet funding.
Package rpc provides direct on-chain helpers for Polygon operations — primarily ERC-20 pUSD transfers from an EOA used by deposit-wallet funding.
stream
Package stream provides typed WebSocket clients for Polymarket CLOB market streams with reconnect and event deduplication.
Package stream provides typed WebSocket clients for Polymarket CLOB market streams with reconnect and event deduplication.
transport
Package transport is the shared HTTP client layer — retry, rate limiting, circuit breaking, and credential redaction.
Package transport is the shared HTTP client layer — retry, rate limiting, circuit breaking, and credential redaction.
wallet
Package wallet re-exports pkg/wallet as a compatibility shim.
Package wallet re-exports pkg/wallet as a compatibility shim.
pkg
bridge
Package bridge is a client for the Polymarket Bridge API — supported assets, deposit addresses, deposit-status polling, and quotes.
Package bridge is a client for the Polymarket Bridge API — supported assets, deposit addresses, deposit-status polling, and quotes.
clob
Package clob exposes the public Polymarket CLOB SDK surface.
Package clob exposes the public Polymarket CLOB SDK surface.
contracts
Package contracts exposes Polymarket Polygon contract addresses and contract-level readiness checks.
Package contracts exposes Polymarket Polygon contract addresses and contract-level readiness checks.
ctf
Package ctf provides utilities for Conditional Token Framework (CTF) on-chain operations on Polymarket.
Package ctf provides utilities for Conditional Token Framework (CTF) on-chain operations on Polymarket.
data
Package data exposes the public, read-only Polymarket Data API SDK surface.
Package data exposes the public, read-only Polymarket Data API SDK surface.
enabletrading
Package enabletrading exposes the SDK primitives for Polymarket's "Enable Trading" UI flow: EOA-signed ClobAuth credential generation and deposit-wallet approval-batch signing.
Package enabletrading exposes the SDK primitives for Polymarket's "Enable Trading" UI flow: EOA-signed ClobAuth credential generation and deposit-wallet approval-batch signing.
experimental/auth
Package auth provides an experimental public API for Polymarket signing primitives.
Package auth provides an experimental public API for Polymarket signing primitives.
experimental/orders
Package orders provides an experimental public API for building and validating Polymarket V2 orders.
Package orders provides an experimental public API for building and validating Polymarket V2 orders.
funding
Package funding exposes explicit on-chain funding operations needed after deposit-wallet onboarding.
Package funding exposes explicit on-chain funding operations needed after deposit-wallet onboarding.
gamma
Package gamma is a read-only client for the Polymarket Gamma API surfaced for embedded use by downstream Go consumers.
Package gamma is a read-only client for the Polymarket Gamma API surfaced for embedded use by downstream Go consumers.
marketdata
Package marketdata turns raw Polymarket market-stream events into per-token orderbook/share-price snapshots.
Package marketdata turns raw Polymarket market-stream events into per-token orderbook/share-price snapshots.
marketresolver
Package marketresolver resolves Polymarket market identifiers — slug, asset, timeframe, or window-start time — into canonical token IDs.
Package marketresolver resolves Polymarket market identifiers — slug, asset, timeframe, or window-start time — into canonical token IDs.
orderbook
Package orderbook is a read-only Polymarket CLOB order-book reader.
Package orderbook is a read-only Polymarket CLOB order-book reader.
orderresults
Package orderresults joins Polymarket account history into one read-only operator report: Data API positions/results plus optional authenticated CLOB open orders and trade history.
Package orderresults joins Polymarket account history into one read-only operator report: Data API positions/results plus optional authenticated CLOB open orders and trade history.
pagination
Package pagination provides generic helpers for paginating cursor-based and offset-based HTTP APIs and for parallelizing batch work.
Package pagination provides generic helpers for paginating cursor-based and offset-based HTTP APIs and for parallelizing batch work.
plugins
Package plugins defines extension points for third-party consumers.
Package plugins defines extension points for third-party consumers.
relayer
Package relayer is the public Go SDK surface for the Polymarket Builder Relayer V2 (https://relayer-v2.polymarket.com).
Package relayer is the public Go SDK surface for the Polymarket Builder Relayer V2 (https://relayer-v2.polymarket.com).
settlement
Package settlement turns redeemable Polymarket V2 positions into deposit-wallet WALLET batches that route through the V2 collateral adapters and return pUSD to the wallet.
Package settlement turns redeemable Polymarket V2 positions into deposit-wallet WALLET batches that route through the V2 collateral adapters and return pUSD to the wallet.
stream
Package stream exposes the public, read-only Polymarket CLOB WebSocket SDK.
Package stream exposes the public, read-only Polymarket CLOB WebSocket SDK.
types
Package types contains public DTOs shared by polygolem SDK packages.
Package types contains public DTOs shared by polygolem SDK packages.
universal
Package universal is a single-stop client for all Polymarket data and authenticated trading operations.
Package universal is a single-stop client for all Polymarket data and authenticated trading operations.
wallet
Package wallet provides deposit-wallet primitives — CREATE2 derivation, status checks, deploy and batch-signing helpers.
Package wallet provides deposit-wallet primitives — CREATE2 derivation, status checks, deploy and batch-signing helpers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL