Python + Rust 组件用于在与 EVM 兼容的区块链上运行 Uniswap (V2、V3、V4)、Curve V1、Solidly V2、Balancer V2 和 Aave V3 的仲裁和清算机器人
Python + Rust 组件用于在与 EVM 兼容的区块链上运行 Uniswap (V2、V3、V4)、Curve V1、Solidly V2、Balancer V2 和 Aave V3 的仲裁和清算机器人
A Rust MEV-bot core with a first-class Python driver shell, for Uniswap (V2, V3, V4), Curve V1, Solidly V2, Balancer V2, and Aave V3 integrations on EVM-compatible blockchains.
Degenbot has two equally first-class consumers sharing one Rust core:
cargo add degenbot (the umbrella crate re-exporting the cores; a git/path dependency until the workspace is published to crates.io) and build a fully functional MEV bot in Rust only.The Rust core is the engine; Python is a driver shell, not a co-implementation. Pool/token state, swap math, event decoding, solvers, the pump loop, and swap encoding all live in Rust core crates; the Python layer provides the user-facing API, orchestration, and configuration. See docs/adr/ADR-005-polars-inspired-three-layer-architecture.md for the architectural vision.
Debugging a failing settlement-arbitrage path, or building your own simulation harness? See
INVESTIGATIONS.md— the simulation oracle driver, the per-contract scaffolder, and the path-fixture toolkit.
Degenbot abstracts the implementation details of Uniswap liquidity pools and their underlying ERC-20 tokens into a set of Rust core crates exposed to Python through a thin PyO3 binding layer. The Rust core owns all performance-critical and stateful logic — pool/token state, swap math, event decoding, solvers, the pump loop, and swap encoding — while the Python companion provides the user-facing API, docstrings, and I/O orchestration.
As of the 0.6.x series the Rust core also owns the operator-facing infrastructure: the settlement-arbitrage engine and pump loop, the in-process revm simulation engine, on-chain price readers, the DB-aware pool/Aave updaters, EIP-1559 transaction signing and submission, and WS/HTTP pub-sub. Python still owns the user-facing API, config, and registries, and — until the ADR-010 0.7 cutover — the SQLAlchemy ORM with its Alembic-stamped session; the Rust degenbot-db crate already owns the schema DDL and file operations behind it (see degenbot database cutover / degenbot database heal).
These classes serve as building blocks for the lessons published by BowTiedDevil on Degen Code.
Ownership is strict, which is what makes both consumption paths first-class: the Rust core owns everything stateful and performance-critical — pool/token state, swap math, event decoding, solvers, the pump loop, and swap encoding — while the Python side owns the user-facing API, orchestration, and configuration. The core crates contain no PyO3 code at all, so a pure-Rust bot (cargo add degenbot) runs without any Python machinery; an in-repo proof is rust/crates/degenbot/examples/standalone_consumer.rs. Architectural decisions — state ownership (ADR-003), FFI topology (ADR-005), schema cutover (ADR-010) — are recorded in the ADR design log, with the crate sources as the last word.
pip, uv, or similar package management toolpip install degenbotgit clone https://github.com/BowTiedDevil/degenbot.git
cd degenbot
uv sync # or: pip install -e .The Bot class is the central session object for all degenbot operations. It manages connections, registries, and provides factory methods for creating pools and tokens:
# Initialize Bot from config file or explicit settings
bot = degenbot.Bot(
config=DegenbotConfig(
default_chain_id=1,
rpc={1: RPC_URL},
database={"path": "~/.config/degenbot/degenbot.db"},
)
)
# Bot constructs the RPC provider from config and enforces its
# eth_chainId matches default_chain_id (fail-fast). No manual provider
# registration is needed.# Create pools and tokens through Bot (I/O-free when possible)
pool = bot.build_pool("0x8ad599c3A0ff1De082011EFDDc58f1908EB6e6D8")
token = bot.build_erc20token("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") # WETH
# Pools are I/O-free - all data injected at construction
print(f"Pool: {pool.name}")
print(f"Token: {token}")
# Calculate swaps without any network calls
amount_out = pool.calculate_tokens_out_from_tokens_in(
token_in=pool.token0,
token_in_quantity=10**18,
)
print(f"Output: {amount_out}")Pool classes are Python companions over Rust-owned pool state — direct construction is impossible (any constructor call raises TypeError); a pool comes into being only by registering in a Bot's Rust state. Use Bot.build_pool() in production (or the make_*_pool test helpers in tests):
# Do NOT do this — the constructor always raises TypeError:
try:
degenbot.UniswapV3Pool("0x8ad599c3A0ff1De082011EFDDc58f1908EB6e6D8") # ← BROKEN!
raise AssertionError("direct construction of a pool should be impossible")
except TypeError:
pass
# Instead, always use Bot to construct pools (registers in Rust state,
# returns the Python companion wrapper):
pool = bot.build_pool("0x8ad599c3A0ff1De082011EFDDc58f1908EB6e6D8")Degenbot pools follow an I/O-free architecture where on-chain data is fetched at construction time and injected into pool objects. After construction, pools are pure calculation objects with no network dependencies. For the Uniswap V2/V3/V4 families (including Aerodrome and Balancer), Bot.build_pool() performs that full choreography on the Rust side; Curve pools and token metadata use the equivalent Python-side builders. Either way, the pool you receive needs no network access at construction time.
Benefits:
Current status: all pool types (V2, V3, V4, Aerodrome, Camelot, Balancer, Curve) are fully I/O-free — no pool class carries provider-dependent methods. For the Uniswap V2/V3/V4 families (including Aerodrome and Balancer), Bot.build_pool() performs the full fetch-and-register choreography and bot.update(pool) refreshes state from chain; Curve pools and token metadata use the remaining Python builders. Either way, state changes enter a pool only as a validated external_update() message — the pool itself never does I/O.
Bot is the central session object that owns all runtime state:
import degenbot
from degenbot.config import DegenbotConfig
# Bot manages connections, registries, and provides factory methods
bot = degenbot.Bot(
config=DegenbotConfig(
default_chain_id=1,
rpc={1: RPC_URL},
database={"path": ":memory:"},
)
)
# The RPC provider is built from config; eth_chainId is enforced to equal
# default_chain_id at construction.
bot.provider # the chain's AlloyProvider (chain_id enforced at construction)
bot.chain_id # 1# All pool/token creation flows through Bot
pool = bot.build_pool("0x8ad599c3A0ff1De082011EFDDc58f1908EB6e6D8")
token = bot.build_erc20token("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
# Bot provides token utilities with caching
balance = bot.get_token_balance(token, "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
approval = bot.get_token_approval(token, owner="0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", spender="0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45")Bot properties:
bot.chain_id - the configured chain ID for this single-chain sessionbot.provider / bot.get_provider() - the chain's AlloyProvider (chain_id enforced at construction)bot.pools - PoolRegistry for created poolsbot.tokens - TokenRegistry for created tokensbot.managed_pools - ManagedPoolRegistry for V4 poolsbot.db - DatabaseSessionManager for state snapshotsLifecycle & refresh: Bot is a context manager — with degenbot.Bot(config=...) as bot: (or an explicit, idempotent bot.close()) tears down the provider, the scoped DB session, and the Rust engine handles. bot.update(pool, block_number=...) is the canonical refresh entry point for the V2/V3/V4 families: it fetches current chain state from the Rust core and pushes pool.external_update() (returns True only when state changed). bot.release_python_state() drops the Python-side tracker/snapshot caches once the Rust engine owns canonical state. Builders are internal to Bot and not exposed publicly. All pool/token creation goes through Bot.build_pool().
build_pool(address) is the universal entry point that auto-resolves pool type from DB, registry, and on-chain probing:
| Pool Type | Method | Supports |
|---|---|---|
| Uniswap V2 | bot.build_pool(address) |
Standard AMM, Camelot, other forks |
| Uniswap V3 | bot.build_pool(address) |
Full tick data, range orders |
| Uniswap V4 | bot.build_managed_pool(address, pool_id=...) |
Singleton architecture with hooks |
| Curve V1 | bot.build_pool(address) |
StableSwap, metapools, lending pools |
When build_pool is called, the pool type is auto-resolved — in order, from the pool registry, the database, and (as a last resort) on-chain probing of the pool contract.
Pools receive state updates via external_update() — a pure-logic method that validates the update and transitions pool state. I/O never touches the pool itself: for the V2/V3/V4 families bot.update(pool) fetches current reserves/slot0/liquidity from the Rust core (Curve/Balancer refresh runs through the remaining Python builders), constructs the family's ExternalUpdate message, and pushes it to the pool:
# Builder fetches state from chain (I/O), constructs update, pushes to pool
update = UniswapV2PoolExternalUpdate(
block_number=block_number,
reserves_token0=reserves0,
reserves_token1=reserves1,
)
pool.external_update(update) # Pure logic — no I/O
# Pool.simulate_swap() previews swaps without st暂无开放 Issues,或尚未同步最近议题。