Skip to content

defipy.twin

The defipy.twin module provides the State Twin abstraction — a protocol-agnostic way to construct exchange objects from declarative pool snapshots.

Key exports

  • StateTwinProvider — ABC defining the snapshot(pool_id, **kwargs) → PoolSnapshot contract
  • MockProvider — synthetic pool snapshots for notebooks, tests, and demos (4 canonical recipes)
  • LiveProvider — on-chain pool snapshots for Uniswap V2 and V3 (v2.1+; requires the [chain] install extra)
  • StateTwinBuilder — dispatches on snapshot type to construct the protocol’s exchange object
  • PoolSnapshot — base class; subclasses V2PoolSnapshot, V3PoolSnapshot, BalancerPoolSnapshot, StableswapPoolSnapshot

Usage — synthetic snapshot

from defipy.twin import MockProvider, StateTwinBuilder
provider = MockProvider()
snapshot = provider.snapshot("eth_dai_v2")
lp = StateTwinBuilder().build(snapshot)
# lp is now a live UniswapExchange — pass it to any primitive
from defipy import CheckPoolHealth
result = CheckPoolHealth().apply(lp)

Usage — live chain snapshot

from defipy.twin import LiveProvider, StateTwinBuilder
provider = LiveProvider("https://eth-mainnet.g.alchemy.com/v2/<key>")
snapshot = provider.snapshot("uniswap_v2:0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc")
lp = StateTwinBuilder().build(snapshot)

The pool_id format for LiveProvider is "<protocol>:<address>". V3 pools use the same shape: "uniswap_v3:0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640". See LiveProvider for the full surface — block pinning, decimal-adjusted reserves, V3 active-liquidity reads, and what’s coming v2.2 (Balancer + Stableswap LiveProvider, V3 tick walking).

Available MockProvider recipes

RecipeProtocolReserves
eth_dai_v2Uniswap V21000 ETH / 100000 DAI
eth_dai_v3Uniswap V31000 ETH / 100000 DAI, full-range, fee=3000
eth_dai_balancer_50_50Balancer 2-asset1000 ETH / 100000 DAI, 50/50 weights
usdc_dai_stableswap_A10Stableswap 2-asset100000 USDC / 100000 DAI, A=10

For the full conceptual treatment — provider/builder split, custom providers, snapshot enrichment fields, the snapshot → builder → primitive pipeline — see the State Twin Concept.