ethswarm-chain-sync 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. ethswarm_chain_sync-0.1.0/.github/workflows/ci.yml +36 -0
  2. ethswarm_chain_sync-0.1.0/.github/workflows/publish.yml +60 -0
  3. ethswarm_chain_sync-0.1.0/.gitignore +7 -0
  4. ethswarm_chain_sync-0.1.0/PKG-INFO +76 -0
  5. ethswarm_chain_sync-0.1.0/README.md +18 -0
  6. ethswarm_chain_sync-0.1.0/docs/README.md +5 -0
  7. ethswarm_chain_sync-0.1.0/docs/data-model.md +65 -0
  8. ethswarm_chain_sync-0.1.0/pyproject.toml +39 -0
  9. ethswarm_chain_sync-0.1.0/src/README.md +5 -0
  10. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/README.md +13 -0
  11. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/__init__.py +26 -0
  12. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/cli.py +183 -0
  13. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/decode.py +159 -0
  14. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/deployments.py +161 -0
  15. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/load.py +101 -0
  16. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/rpc.py +150 -0
  17. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/schema.py +89 -0
  18. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/store.py +174 -0
  19. ethswarm_chain_sync-0.1.0/src/ethswarm_chain_sync/sync.py +187 -0
  20. ethswarm_chain_sync-0.1.0/tests/README.md +9 -0
  21. ethswarm_chain_sync-0.1.0/tests/conftest.py +198 -0
  22. ethswarm_chain_sync-0.1.0/tests/test_decode.py +161 -0
  23. ethswarm_chain_sync-0.1.0/tests/test_load.py +69 -0
  24. ethswarm_chain_sync-0.1.0/tests/test_selection_and_rpc.py +194 -0
  25. ethswarm_chain_sync-0.1.0/tests/test_sync.py +139 -0
  26. ethswarm_chain_sync-0.1.0/uv.lock +891 -0
@@ -0,0 +1,36 @@
1
+ name: CI
2
+
3
+ # Lint and the offline test suite, on every PR and every push to main. Also callable
4
+ # from publish.yml so a release cannot be published unless this passes.
5
+
6
+ on:
7
+ pull_request:
8
+ push:
9
+ branches: [main]
10
+ workflow_call:
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ test:
17
+ runs-on: ubuntu-latest
18
+ strategy:
19
+ fail-fast: false
20
+ matrix:
21
+ python-version: ["3.11", "3.12", "3.13", "3.14"]
22
+ steps:
23
+ - uses: actions/checkout@v5
24
+ with:
25
+ fetch-depth: 0 # hatch-vcs derives the version from tags
26
+ persist-credentials: false
27
+
28
+ - uses: astral-sh/setup-uv@v5
29
+
30
+ - name: Lint
31
+ run: |
32
+ uvx ruff check src tests
33
+ uvx ruff format --check src tests
34
+
35
+ - name: Test
36
+ run: uv run --python ${{ matrix.python-version }} pytest -q
@@ -0,0 +1,60 @@
1
+ name: Publish to PyPI
2
+
3
+ # Publishes a release when a numbered version tag (vX.Y.Z) is pushed for a commit on
4
+ # main. The version comes from the tag via hatch-vcs, so tagging a merged commit on main
5
+ # is the act of releasing:
6
+ #
7
+ # git checkout main && git pull && git tag v0.1.0 && git push origin v0.1.0
8
+ #
9
+ # The publish job is gated on ci.yml, and refuses tags whose commit is not on main.
10
+ # Uses PyPI trusted publishing (OIDC); the workflow filename and the `pypi` environment
11
+ # are part of the trusted-publisher configuration on PyPI.
12
+
13
+ on:
14
+ push:
15
+ tags: ["v[0-9]+.[0-9]+.[0-9]+"]
16
+
17
+ permissions: {}
18
+
19
+ jobs:
20
+ check:
21
+ uses: ./.github/workflows/ci.yml
22
+ permissions:
23
+ contents: read
24
+
25
+ publish:
26
+ name: Build and publish
27
+ needs: check
28
+ runs-on: ubuntu-latest
29
+ environment:
30
+ name: pypi
31
+ url: https://pypi.org/project/ethswarm-chain-sync/
32
+ permissions:
33
+ contents: read
34
+ id-token: write # OIDC token for PyPI trusted publishing
35
+ steps:
36
+ - uses: actions/checkout@v5
37
+ with:
38
+ fetch-depth: 0
39
+ persist-credentials: false
40
+
41
+ - name: Require the tagged commit to be on main
42
+ run: |
43
+ git fetch --no-tags origin main
44
+ git merge-base --is-ancestor "$GITHUB_SHA" origin/main \
45
+ || { echo "::error::$GITHUB_REF_NAME is not on main"; exit 1; }
46
+
47
+ - uses: astral-sh/setup-uv@v5
48
+
49
+ - name: Build sdist and wheel
50
+ run: uv build
51
+
52
+ - name: Check built version matches tag
53
+ run: |
54
+ want="${GITHUB_REF_NAME#v}"
55
+ ls dist/
56
+ test -f "dist/ethswarm_chain_sync-${want}.tar.gz" \
57
+ || { echo "::error::built version does not match tag $GITHUB_REF_NAME"; exit 1; }
58
+
59
+ - name: Publish
60
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ .ethswarm-deployments/
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: ethswarm-chain-sync
3
+ Version: 0.1.0
4
+ Summary: Sync Swarm storage-incentives contract events into a local JSONLines cache
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: eth-abi>=5
7
+ Requires-Dist: eth-hash[pycryptodome]>=0.7
8
+ Requires-Dist: ethswarm-deployments
9
+ Requires-Dist: requests>=2.31
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ethswarm-chain-sync data model
13
+
14
+ ethswarm-chain-sync syncs events emitted by the Swarm storage-incentives contracts (every deployed version, on Gnosis "mainnet" and Sepolia "testnet") into a local JSONLines cache, and loads that cache back as a list of objects. It follows the acquisition layer of the VolumeRegistry indexer (`swarm-volume-registry/services/indexer`): a finalized-only, event-sourced log cache, partitioned per event type, with web3 confined to the acquisition and decode step. It has no projector.
15
+
16
+ ## Sources
17
+
18
+ Deployments (address, deployment block, ABI) come from the `ethswarm-deployments` package's user-local cache. A sync target is one distinct contract address. Each target's event schemas come from that address's own ABI, so a log is decoded by `(address, topic0)`, never by event name alone. This disambiguates names shared across contracts (`Paused`, `RoleGranted`, `PriceUpdate`) and across versions of one contract (`StakeUpdated` has three signatures; the field order of the `WinnerSelected` struct changed in v0.6.0).
19
+
20
+ Acquisition reads `eth_getLogs` up to the chain's `finalized` block only, so the cache never needs reorg handling.
21
+
22
+ ## Row
23
+
24
+ One row per log:
25
+
26
+ | field | type | meaning |
27
+ |---|---|---|
28
+ | `chain_id` | int | 100 (Gnosis) or 11155111 (Sepolia) |
29
+ | `contract` | str | canonical contract name, e.g. `Redistribution` |
30
+ | `version` | str | first storage-incentives release containing this address |
31
+ | `address` | str | emitting contract, lowercase hex |
32
+ | `event` | str | event key: the event name, or its full signature if the ABI overloads the name |
33
+ | `signature` | str | canonical signature, e.g. `Committed(uint256,bytes32,uint8)` |
34
+ | `block_number` | int | |
35
+ | `block_timestamp` | str | UTC ISO 8601 (`...Z`), from the log's `blockTimestamp`; `load()` returns a timezone-aware `datetime` |
36
+ | `transaction_hash` | str | lowercase hex |
37
+ | `transaction_index` | int | |
38
+ | `log_index` | int | `(block_number, log_index)` is chain order |
39
+ | `args` | object | decoded event arguments keyed by ABI parameter name |
40
+
41
+ Decoding of `args` is plain ABI decoding, with names attached. Addresses are lowercase hex, `bytes`/`bytesN` are `0x` hex, integers are exact JSON integers (uint256 values are not rounded), and structs are objects keyed by component name, recursively and inside arrays. An indexed dynamic value (string, bytes, array, struct) only appears in the log as its keccak hash, and is stored as that hash. The Swarm contracts have no enums, so no value mapping is applied.
42
+
43
+ ## On disk
44
+
45
+ ```
46
+ <store-dir>/ --store-dir, $ETHSWARM_CHAIN_SYNC_STORE, or ~/.cache/ethswarm-chain-sync
47
+ <chain_id>/
48
+ <Contract>_<address>/ one directory per deployed contract
49
+ <event>.jsonl one append-only file per event, rows in chain order
50
+ head.json {"events": {"<event>": {"block": N, "size": B}}}
51
+ ```
52
+
53
+ Each event has its own checkpoint: the last block synced (inclusive) and the byte size of its file at that block. Syncing a subset of events and later a superset therefore works, and each event resumes from its own checkpoint. On first sync an event starts at the contract's deployment block.
54
+
55
+ Each block range is appended and fsynced before `head.json` is atomically replaced. A sync that is interrupted at any point leaves each file as its checkpointed prefix plus, possibly, an uncheckpointed tail, which may include a torn final line. The next sync truncates each file back to its checkpointed size before resuming, so the files are exactly-once (no duplicate or partial rows), and an interrupted and resumed sync produces the same bytes as an uninterrupted one. The loader reads each file only up to its checkpointed size, so it is safe to load while a sync is running.
56
+
57
+ The store is a cache. Deleting a contract's directory makes the next sync rebuild it from the deployment block.
58
+
59
+ ## Usage
60
+
61
+ ```
62
+ ethswarm-chain-sync sync # all non-token contracts, mainnet
63
+ ethswarm-chain-sync sync -c PostageStamp -e BatchCreated # one event, every PostageStamp deployment
64
+ ethswarm-chain-sync sync -c Redistribution@v0.9.4 # one deployment
65
+ ethswarm-chain-sync sync -n testnet -c 0x... # by address, on Sepolia
66
+ ethswarm-chain-sync status -c StakeRegistry # checkpoints, no RPC
67
+ ```
68
+
69
+ The RPC endpoint is `--rpc-url`, else `$GNO_RPC_URL` (mainnet) or `$SEP_RPC_URL` (testnet). `Token`/`TestToken` are only synced when named with `-c`.
70
+
71
+ ```python
72
+ import ethswarm_chain_sync as ecs
73
+
74
+ rows = ecs.load("PostageStamp", "BatchCreated") # list[dict], chain order
75
+ rows = ecs.load(event=["Committed", "Revealed"], network="testnet")
76
+ ```
@@ -0,0 +1,18 @@
1
+ # ethswarm-chain-sync
2
+
3
+ Syncs events from the [Swarm storage-incentives](https://github.com/ethersphere/storage-incentives) contracts (PostageStamp, PriceOracle, Redistribution, StakeRegistry and the BZZ token, across every deployed version on Gnosis Chain and Sepolia) into a local JSONLines cache, and loads them back as a list of objects.
4
+
5
+ The purpose is to give analysis code a complete, decoded event history of the Swarm contracts without each project re-implementing log acquisition. A command line tool fetches events up to the chain's finalized block, decodes them against the ABI of the specific deployment that emitted them, and checkpoints progress so that an interrupted sync resumes exactly where it stopped. Imported as a Python package, it reads the cache back with no RPC or web3 dependency at read time. Deployment addresses and ABIs come from [ethswarm-deployments](https://github.com/shtukaresearch/ethswarm-deployments).
6
+
7
+ See `docs/data-model.md` for the row format, on-disk layout and usage.
8
+
9
+ | path | description |
10
+ |---|---|
11
+ | `.github/workflows/ci.yml` | Lint and tests on Python 3.11–3.14 for every PR and push to main. |
12
+ | `.github/workflows/publish.yml` | Builds and publishes to PyPI when a `vX.Y.Z` tag is pushed for a commit on main. |
13
+ | `.gitignore` | Ignores virtualenvs, caches, build output and the project-local deployments cache. |
14
+ | `pyproject.toml` | Package metadata, dependencies, the `ethswarm-chain-sync` entry point, and hatch/pytest/ruff configuration. |
15
+ | `uv.lock` | Locked dependency versions for uv. |
16
+ | `docs/` | Project documentation. |
17
+ | `src/` | Package source. |
18
+ | `tests/` | Pytest suite (offline, against a fake RPC). |
@@ -0,0 +1,5 @@
1
+ # docs
2
+
3
+ | file | description |
4
+ |---|---|
5
+ | `data-model.md` | Data sources, row schema, on-disk store layout, checkpoint and resume semantics, and usage. |
@@ -0,0 +1,65 @@
1
+ # ethswarm-chain-sync data model
2
+
3
+ ethswarm-chain-sync syncs events emitted by the Swarm storage-incentives contracts (every deployed version, on Gnosis "mainnet" and Sepolia "testnet") into a local JSONLines cache, and loads that cache back as a list of objects. It follows the acquisition layer of the VolumeRegistry indexer (`swarm-volume-registry/services/indexer`): a finalized-only, event-sourced log cache, partitioned per event type, with web3 confined to the acquisition and decode step. It has no projector.
4
+
5
+ ## Sources
6
+
7
+ Deployments (address, deployment block, ABI) come from the `ethswarm-deployments` package's user-local cache. A sync target is one distinct contract address. Each target's event schemas come from that address's own ABI, so a log is decoded by `(address, topic0)`, never by event name alone. This disambiguates names shared across contracts (`Paused`, `RoleGranted`, `PriceUpdate`) and across versions of one contract (`StakeUpdated` has three signatures; the field order of the `WinnerSelected` struct changed in v0.6.0).
8
+
9
+ Acquisition reads `eth_getLogs` up to the chain's `finalized` block only, so the cache never needs reorg handling.
10
+
11
+ ## Row
12
+
13
+ One row per log:
14
+
15
+ | field | type | meaning |
16
+ |---|---|---|
17
+ | `chain_id` | int | 100 (Gnosis) or 11155111 (Sepolia) |
18
+ | `contract` | str | canonical contract name, e.g. `Redistribution` |
19
+ | `version` | str | first storage-incentives release containing this address |
20
+ | `address` | str | emitting contract, lowercase hex |
21
+ | `event` | str | event key: the event name, or its full signature if the ABI overloads the name |
22
+ | `signature` | str | canonical signature, e.g. `Committed(uint256,bytes32,uint8)` |
23
+ | `block_number` | int | |
24
+ | `block_timestamp` | str | UTC ISO 8601 (`...Z`), from the log's `blockTimestamp`; `load()` returns a timezone-aware `datetime` |
25
+ | `transaction_hash` | str | lowercase hex |
26
+ | `transaction_index` | int | |
27
+ | `log_index` | int | `(block_number, log_index)` is chain order |
28
+ | `args` | object | decoded event arguments keyed by ABI parameter name |
29
+
30
+ Decoding of `args` is plain ABI decoding, with names attached. Addresses are lowercase hex, `bytes`/`bytesN` are `0x` hex, integers are exact JSON integers (uint256 values are not rounded), and structs are objects keyed by component name, recursively and inside arrays. An indexed dynamic value (string, bytes, array, struct) only appears in the log as its keccak hash, and is stored as that hash. The Swarm contracts have no enums, so no value mapping is applied.
31
+
32
+ ## On disk
33
+
34
+ ```
35
+ <store-dir>/ --store-dir, $ETHSWARM_CHAIN_SYNC_STORE, or ~/.cache/ethswarm-chain-sync
36
+ <chain_id>/
37
+ <Contract>_<address>/ one directory per deployed contract
38
+ <event>.jsonl one append-only file per event, rows in chain order
39
+ head.json {"events": {"<event>": {"block": N, "size": B}}}
40
+ ```
41
+
42
+ Each event has its own checkpoint: the last block synced (inclusive) and the byte size of its file at that block. Syncing a subset of events and later a superset therefore works, and each event resumes from its own checkpoint. On first sync an event starts at the contract's deployment block.
43
+
44
+ Each block range is appended and fsynced before `head.json` is atomically replaced. A sync that is interrupted at any point leaves each file as its checkpointed prefix plus, possibly, an uncheckpointed tail, which may include a torn final line. The next sync truncates each file back to its checkpointed size before resuming, so the files are exactly-once (no duplicate or partial rows), and an interrupted and resumed sync produces the same bytes as an uninterrupted one. The loader reads each file only up to its checkpointed size, so it is safe to load while a sync is running.
45
+
46
+ The store is a cache. Deleting a contract's directory makes the next sync rebuild it from the deployment block.
47
+
48
+ ## Usage
49
+
50
+ ```
51
+ ethswarm-chain-sync sync # all non-token contracts, mainnet
52
+ ethswarm-chain-sync sync -c PostageStamp -e BatchCreated # one event, every PostageStamp deployment
53
+ ethswarm-chain-sync sync -c Redistribution@v0.9.4 # one deployment
54
+ ethswarm-chain-sync sync -n testnet -c 0x... # by address, on Sepolia
55
+ ethswarm-chain-sync status -c StakeRegistry # checkpoints, no RPC
56
+ ```
57
+
58
+ The RPC endpoint is `--rpc-url`, else `$GNO_RPC_URL` (mainnet) or `$SEP_RPC_URL` (testnet). `Token`/`TestToken` are only synced when named with `-c`.
59
+
60
+ ```python
61
+ import ethswarm_chain_sync as ecs
62
+
63
+ rows = ecs.load("PostageStamp", "BatchCreated") # list[dict], chain order
64
+ rows = ecs.load(event=["Committed", "Revealed"], network="testnet")
65
+ ```
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "ethswarm-chain-sync"
3
+ dynamic = ["version"]
4
+ description = "Sync Swarm storage-incentives contract events into a local JSONLines cache"
5
+ readme = "docs/data-model.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "eth-abi>=5",
9
+ "eth-hash[pycryptodome]>=0.7",
10
+ "ethswarm-deployments",
11
+ "requests>=2.31",
12
+ ]
13
+
14
+ [project.scripts]
15
+ ethswarm-chain-sync = "ethswarm_chain_sync.cli:main"
16
+
17
+ [build-system]
18
+ requires = ["hatchling", "hatch-vcs"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [tool.hatch.version]
22
+ source = "vcs"
23
+ fallback-version = "0.0.0"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/ethswarm_chain_sync"]
27
+
28
+ [dependency-groups]
29
+ dev = ["pytest>=8"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
33
+ pythonpath = ["src", "tests"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+
38
+ [tool.ruff.lint]
39
+ select = ["E", "F", "I", "UP", "B"]
@@ -0,0 +1,5 @@
1
+ # src
2
+
3
+ | path | description |
4
+ |---|---|
5
+ | `ethswarm_chain_sync/` | The `ethswarm_chain_sync` package. |
@@ -0,0 +1,13 @@
1
+ # ethswarm_chain_sync
2
+
3
+ | file | description |
4
+ |---|---|
5
+ | `__init__.py` | Public API: `load`, `iter_rows` and `__version__`. |
6
+ | `cli.py` | Command line entry point with the `sync` and `status` subcommands. |
7
+ | `decode.py` | Decodes raw `eth_getLogs` entries into named, JSON-ready rows using `eth_abi`. |
8
+ | `deployments.py` | Resolves contract and event selectors into sync targets from the `ethswarm-deployments` cache. |
9
+ | `load.py` | Reads the cache back as rows, filtered by contract, event, address and network, in chain order. |
10
+ | `rpc.py` | JSON-RPC client protocol and HTTP implementation with short timeouts, retries and range-too-large detection. |
11
+ | `schema.py` | Builds per-deployment event schemas (signature, `topic0`, inputs, store key) from an ABI. |
12
+ | `store.py` | JSONLines store layout, per-event checkpoints, tail rewind on resume, and the per-deployment lock. |
13
+ | `sync.py` | Acquisition engine: concurrent range fetches committed in order, with range bisection and checkpointing. |
@@ -0,0 +1,26 @@
1
+ """Sync Swarm storage-incentives contract events into a local JSONLines cache.
2
+
3
+ Command line: ``ethswarm-chain-sync sync`` fetches and decodes events from the deployed
4
+ storage-incentives contracts (every version, per ``ethswarm-deployments``) up to the
5
+ chain's ``finalized`` block, resuming from each event's checkpoint.
6
+
7
+ As a library, :func:`load` returns the cached rows as a list of dicts in chain order::
8
+
9
+ import ethswarm_chain_sync as ecs
10
+
11
+ rows = ecs.load("PostageStamp", "BatchCreated")
12
+ rows[0]["args"]["batchId"]
13
+
14
+ Row format and on-disk layout are described in ``docs/data-model.md``.
15
+ """
16
+
17
+ from importlib.metadata import PackageNotFoundError, version
18
+
19
+ from .load import iter_rows, load
20
+
21
+ try:
22
+ __version__ = version("ethswarm-chain-sync")
23
+ except PackageNotFoundError: # running from a source tree without installation
24
+ __version__ = "0.0.0"
25
+
26
+ __all__ = ["__version__", "iter_rows", "load"]
@@ -0,0 +1,183 @@
1
+ """Command line: ``ethswarm-chain-sync {sync,status}``.
2
+
3
+ ``sync`` resolves the selected deployments (``--contract`` / ``--event``, see
4
+ :func:`~ethswarm_chain_sync.deployments.resolve_targets`), reads the chain's
5
+ ``finalized`` block once, and syncs each target up to it. Each event starts from its
6
+ stored checkpoint, or from the contract's deployment block on first sync.
7
+
8
+ ``status`` prints the same selection with each event's checkpoint, without touching the
9
+ chain.
10
+
11
+ The RPC endpoint is ``--rpc-url``, else ``$<SHORT>_RPC_URL`` where ``SHORT`` is the
12
+ network's EIP-3770 chain short name (``GNO`` for mainnet/Gnosis, ``SEP`` for
13
+ testnet/Sepolia).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import os
20
+ import sys
21
+ import time
22
+
23
+ from . import __version__, store
24
+ from .deployments import NETWORK_SHORT_NAMES, SelectionError, Target, resolve_targets
25
+ from .rpc import HttpRpcClient
26
+ from .sync import DEFAULT_CHUNK_SIZE, DEFAULT_WORKERS, sync_target
27
+
28
+
29
+ class _Progress:
30
+ """Per-target progress line on stderr, redrawn in place on a terminal."""
31
+
32
+ def __init__(self, enabled: bool) -> None:
33
+ self.enabled = enabled
34
+ self.inplace = sys.stderr.isatty()
35
+ self.last = 0.0
36
+
37
+ def __call__(self, target: Target, block: int, to_block: int, rows: int) -> None:
38
+ now = time.monotonic()
39
+ if not self.enabled or (now - self.last < 0.5 and block != to_block):
40
+ return
41
+ self.last = now
42
+ line = f" {target.label}: block {block}/{to_block}, {rows} rows"
43
+ if self.inplace:
44
+ print(f"\r\033[K{line}", end="", file=sys.stderr, flush=True)
45
+ else:
46
+ print(line, file=sys.stderr, flush=True)
47
+
48
+ def done(self) -> None:
49
+ if self.enabled and self.inplace:
50
+ print(file=sys.stderr)
51
+
52
+
53
+ def _targets(args) -> list[Target]:
54
+ return resolve_targets(args.network, args.contract or (), args.event or ())
55
+
56
+
57
+ def cmd_sync(args) -> int:
58
+ """Sync every selected target up to ``finalized`` (or ``--to-block``)."""
59
+ url = args.rpc_url or os.environ.get(f"{NETWORK_SHORT_NAMES[args.network]}_RPC_URL")
60
+ if not url:
61
+ env = f"{NETWORK_SHORT_NAMES[args.network]}_RPC_URL"
62
+ print(f"error: no RPC endpoint; pass --rpc-url or set ${env}", file=sys.stderr)
63
+ return 2
64
+ targets = _targets(args)
65
+ rpc = HttpRpcClient(url, timeout=args.timeout)
66
+ finalized = rpc.finalized_block()
67
+ to_block = finalized if args.to_block is None else args.to_block
68
+ if to_block > finalized:
69
+ print(f"error: --to-block {to_block} is past finalized {finalized}", file=sys.stderr)
70
+ return 2
71
+ store_dir = store.resolve_store_dir(args.store_dir)
72
+ print(
73
+ f"store {store_dir}; syncing {len(targets)} contract(s) to block {to_block}",
74
+ file=sys.stderr,
75
+ )
76
+ progress = _Progress(args.progress if args.progress is not None else sys.stderr.isatty())
77
+ for target in targets:
78
+ print(f"{target.label}: {len(target.selected)} event(s)", file=sys.stderr)
79
+ result = sync_target(
80
+ rpc,
81
+ store_dir,
82
+ target,
83
+ to_block=to_block,
84
+ chunk_size=args.chunk_size,
85
+ workers=args.workers,
86
+ progress=progress,
87
+ )
88
+ progress.done()
89
+ total = sum(result.rows.values())
90
+ detail = ", ".join(f"{k}={n}" for k, n in sorted(result.rows.items()) if n)
91
+ print(f" +{total} rows" + (f" ({detail})" if detail else ""), file=sys.stderr)
92
+ return 0
93
+
94
+
95
+ def cmd_status(args) -> int:
96
+ """Print each selected event's checkpoint."""
97
+ store_dir = store.resolve_store_dir(args.store_dir)
98
+ for t in _targets(args):
99
+ dep_dir = store.deployment_dir(store_dir, t.chain_id, t.contract, t.address)
100
+ cps = store.load_checkpoints(dep_dir)
101
+ print(f"{t.contract}@{t.version} {t.address} (deployed at {t.start_block})")
102
+ for s in t.selected_schemas():
103
+ cp = cps.get(s.key)
104
+ state = f"block {cp.block}, {cp.size} bytes" if cp else "not synced"
105
+ print(f" {s.key:<32} {state}")
106
+ return 0
107
+
108
+
109
+ def _add_selection(p: argparse.ArgumentParser) -> None:
110
+ p.add_argument("-n", "--network", choices=sorted(NETWORK_SHORT_NAMES), default="mainnet")
111
+ p.add_argument(
112
+ "-c",
113
+ "--contract",
114
+ action="append",
115
+ metavar="SEL",
116
+ help="contract name, name@version, or address (repeatable; default: all non-token)",
117
+ )
118
+ p.add_argument(
119
+ "-e",
120
+ "--event",
121
+ action="append",
122
+ metavar="NAME",
123
+ help="event name or signature (repeatable; default: all events)",
124
+ )
125
+ p.add_argument(
126
+ "--store-dir",
127
+ help=f"cache directory (default: ${store.STORE_DIR_ENV} or {store.default_store_dir()})",
128
+ )
129
+
130
+
131
+ def build_parser() -> argparse.ArgumentParser:
132
+ """The argument parser (exposed for tests)."""
133
+ parser = argparse.ArgumentParser(prog="ethswarm-chain-sync", description=__doc__.split("\n")[0])
134
+ parser.add_argument("--version", action="version", version=__version__)
135
+ sub = parser.add_subparsers(dest="command", required=True)
136
+
137
+ p_sync = sub.add_parser("sync", help="sync events into the cache up to finalized")
138
+ _add_selection(p_sync)
139
+ p_sync.add_argument("--rpc-url", help="JSON-RPC endpoint (default: $GNO_RPC_URL/$SEP_RPC_URL)")
140
+ p_sync.add_argument("--to-block", type=int, help="sync to this block instead of finalized")
141
+ p_sync.add_argument(
142
+ "--chunk-size",
143
+ type=int,
144
+ default=DEFAULT_CHUNK_SIZE,
145
+ help="blocks per eth_getLogs (default: %(default)s)",
146
+ )
147
+ p_sync.add_argument(
148
+ "--workers",
149
+ type=int,
150
+ default=DEFAULT_WORKERS,
151
+ help="concurrent eth_getLogs requests (default: %(default)s)",
152
+ )
153
+ p_sync.add_argument(
154
+ "--timeout",
155
+ type=float,
156
+ default=3.0,
157
+ help="per-request timeout, seconds (default: %(default)s)",
158
+ )
159
+ p_sync.add_argument(
160
+ "--progress",
161
+ action=argparse.BooleanOptionalAction,
162
+ default=None,
163
+ help="show progress (default: when stderr is a terminal)",
164
+ )
165
+ p_sync.set_defaults(func=cmd_sync)
166
+
167
+ p_status = sub.add_parser("status", help="show checkpoints of the selected events")
168
+ _add_selection(p_status)
169
+ p_status.set_defaults(func=cmd_status)
170
+ return parser
171
+
172
+
173
+ def main(argv: list[str] | None = None) -> int:
174
+ """Entry point; returns the process exit code."""
175
+ args = build_parser().parse_args(argv)
176
+ try:
177
+ return args.func(args)
178
+ except (SelectionError, store.StoreLockedError) as exc:
179
+ print(f"error: {exc}", file=sys.stderr)
180
+ return 2
181
+ except KeyboardInterrupt:
182
+ print("\ninterrupted; progress is checkpointed, rerun to resume", file=sys.stderr)
183
+ return 130