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 thesnapshot(pool_id, **kwargs) → PoolSnapshotcontractMockProvider— 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 objectPoolSnapshot— base class; subclassesV2PoolSnapshot,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 primitivefrom defipy import CheckPoolHealthresult = 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
| Recipe | Protocol | Reserves |
|---|---|---|
eth_dai_v2 | Uniswap V2 | 1000 ETH / 100000 DAI |
eth_dai_v3 | Uniswap V3 | 1000 ETH / 100000 DAI, full-range, fee=3000 |
eth_dai_balancer_50_50 | Balancer 2-asset | 1000 ETH / 100000 DAI, 50/50 weights |
usdc_dai_stableswap_A10 | Stableswap 2-asset | 100000 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.