Ai! Jack!v2026.04.01-f12
← 홈GitHub 트렌딩

nahrek/polyledger

원문 보기
★ 621109 forksPython미국 (추정)

AI 분석

•Polymarket 데이터 인덱서 → 시장 메타데이터와 Polygon 체결 이벤트를 DuckDB 파일 하나로 통합
•데이터와 진행 지점을 함께 커밋하고 중복 삽입을 방지해 중단 후 재개에 강한 구조
•OrderFilled 기반 체결 데이터와 전체 주문장 이력의 구분, 외부 API 의존성 검토 필요

Resumable Polymarket indexer: CLOB market metadata plus on-chain trades from Polygon, in one DuckDB file you can query with SQL

검증 정보

출처
github.com
피드
GitHub 트렌딩
수집/분석 기준
2026. 9. 8. 오전 9:00
원문 확인
원문 열기

본문

# PolyLedger

A resumable indexer for Polymarket market metadata and on-chain trade data, backed by DuckDB.

PolyLedger pulls every market from the Polymarket CLOB API, streams every OrderFilled event from Polygon via [Envio HyperSync](https://envio.dev), and writes both into a single DuckDB file you can query with SQL immediately.


## Table of contents

•[Features](#features)
•[Requirements](#requirements)
•[Installation](#installation)
•[Quick start](#quick-start)
•[CLI reference](#cli-reference)
•[Data model](#data-model)
•[Indexed contracts](#indexed-contracts)
•[Configuration](#configuration)
•[Design notes](#design-notes)
•[Development](#development)
•[Limitations](#limitations)
•[License](#license)

## Features

•Resumable by construction. Rows and the block cursor are committed in a single transaction, so an interrupted run resumes exactly where it stopped.
•Idempotent writes. order_fills is keyed on (transaction_hash, log_index) and inserted with ON CONFLICT DO NOTHING. Re-running a range is a no-op.
•DuckDB storage. Columnar compression, real types, indexes, and SQL joins, all in one file on disk. No server.
•Both contract generations. Decodes the V2 OrderFilled layout and the older V1 one, with separate checkpoints per stream.
•Schema validation. Every API response passes through Pydantic models, so an upstream format change fails loudly instead of writing nulls for hours.
•Resilient networking. Exponential backoff with jitter, Retry-After support, and a shared token-bucket rate limiter across all REST sources.
•Gap recovery. Token ids missing from the CLOB listing are flagged and backfilled from the Gamma API rather than silently dropped.
•Parquet export. One command dumps every table for use with pandas, polars, or Spark.

## Requirements

•Python 3.11 or newer
•A HyperSync API token (required since November 2025; the free tier is sufficient). Register at [envio.dev](https://envio.dev).

The CLOB and Gamma APIs are public and need no credentials.

## Installation

git clone https://github.com/nahrek/polyledger
cd polyledger
python -m venv .venv
.venv\Scripts\activate.bat
pip install -e .

Then configure the HyperSync token. Copy .env.example to .env, open it in any

editor, and set HYPERSYNC_BEARER_TOKEN. PolyLedger reads .env from the working

directory on startup, so there is no export step. Real environment variables still

take precedence if you prefer to set them that way.

## Quick start

Run the full pipeline:

polyledger sync

The first backfill is slow. On the free HyperSync tier it takes anywhere from a few hours to a couple of days depending on how much history you want. It is safe to interrupt at any point. Every subsequent run is incremental and finishes in seconds.

To verify the setup on a small slice first:

polyledger markets                    # metadata only, a few minutes
polyledger chain --max-blocks 200000  # roughly five days of Polygon history
polyledger stats

stats reports what is actually in the database:

  markets          14231
  tokens           28455
  fills            1204773
  unmatched_fills  392
  first_block      75014820
  last_block       75214820
  first_time       2026-05-14 08:11:23
  last_time        2026-05-19 03:44:02
  checkpoints:
    order_filled:v2: block 75214820, 1204773 rows, updated 2026-09-02 15:11:23

Then query it:

polyledger query "SELECT question, sum(usd_size) AS volume FROM trades GROUP BY 1 ORDER BY 2 DESC LIMIT 10"

## CLI reference

CommandDescription
polyledger markets [--backfill]Sync market metadata from the CLOB. --backfill also resolves unmatched token ids via Gamma.
polyledger chain [options]Index OrderFilled logs from Polygon.
polyledger trades [--drop-unmatched]Materialise the joined trades_mat table.
polyledger sync [options]Run markets → chain → backfill → trades in order.
polyledger statsShow row counts, block range, and checkpoints.
polyledger export [--out DIR]Write every table to Parquet.
polyledger query "SELECT ..."Run one SQL statement and print the result.

chain options:

FlagDescription
`--contracts v2\v1\all`Which exchange generation to index. Default v2.
--from-block NOverride the start block. Ignored if a checkpoint exists.
--to-block NStop at this block.
--max-blocks NIndex at most this many blocks, then exit.

Global flags: --db PATH to use a different database file, -v for verbose logging.

The polyledger executable is installed by pip install -e .. Without installing, python -m polyledger and python -m polyledger.cli are equivalent. The entry point is main() in polyledger/cli.py.

## Data model

### trades

관련 아이템