Skip to content
Crypto.world

Research

State Twins: An Off-Chain Substrate for Agentic Reasoning over Decentralized Finance Protocols

Agentic DeFi systems today are "reactive": a reasoning model is wired directly to chain reads and chain writes through a thin RPC wrapper, so every question the agent asks costs a round trip or a…

State Twins: An Off-Chain Substrate for Agentic Reasoning over Decentralized Finance Protocols
arXiv
2605.11522
Published
2026-05-12
Authors
Ian C. Moore

AI summary

Overview

Research area: Decentralized finance (DeFi) infrastructure — specifically automated market maker (AMM) state modelling, agentic AI systems, and the software substrate that connects large language models to on-chain protocol mathematics. Submitted under Distributed, Parallel, and Cluster Computing (arXiv:2605.11522v1 [cs.DC], 12 May 2026) by Ian C. Moore, PhD (Principal, DeFiMind).

Technical level: Advanced. The paper combines control-theoretic state-space formalism, a stated fidelity proof, and open-source SDK design; readers need comfort with AMM invariants and agent architectures, though the prose is unusually readable for the formalism it carries.

Scope (one sentence): The paper defines, proves bounds for, and ships an off-chain "State Twin" — a typed, replayable, forkable in-memory replica of an AMM pool — as the missing substrate layer for agents that need to reason counterfactually about DeFi protocols instead of merely reading and writing to chain.

What This Paper Is About

Agentic DeFi systems today are "reactive": a reasoning model is wired directly to chain reads and chain writes through a thin RPC wrapper, so every question the agent asks costs a round trip or a real transaction. Moore argues this coupling is structural rather than a performance problem — the agent's action space is bounded by block confirmation latency, gas, and sequential transaction ordering, and counterfactual or multi-scenario queries are simply not expressible. Because AMM pool state evolves by a known, deterministic transition function, the paper's goal is to formalize an off-chain replica that preserves the protocol's exact mathematics while permitting the operations on-chain state cannot: forking, replay, branching, and counterfactual rollout.

Key Contributions

  1. A dynamical-systems formalization of four AMM families. Uniswap V2, Uniswap V3, Balancer, and Stableswap are each expressed as a discrete-time controlled system x_{k+1} = f(x_k, u_k, w_k), y_k = h(x_k), separating state, input, and observation — and showing that reactive architectures conflate all three.

  2. The State Twin definition and a quantitative fidelity bound. The twin is defined by four properties — state fidelity (T1), observational equivalence (T2), transitional equivalence (T3), and independent forking (T4) — with a "State Twin Fidelity" proposition bounding divergence between twin and chain as |h_K(x̂_n) − h_K(x_n)| ≤ nB under the discretized constant-product update.

  3. The provider/builder factorization. A Provider → Snapshot → Builder → Twin → Primitive path decouples the source of pool state from the shape of pool state, reducing adapter count from |sources| × |protocols| to |sources| + |protocols|. A corollary argument (Remark 1) claims any architecture supporting counterfactual queries must contain a local realization of the state space accessible independently of the chain-read map.

  4. DeFiPy v2 as reference implementation. An open-source Python toolkit shipping 7 core operational primitives (Swap, Join, AddLiquidity, etc.), 21 typed analytical primitives across 9 categories, a twin substrate (MockProvider, LiveProvider, and a demonstrated CSVProvider), and a reference Model Context Protocol server exposing 10 primitives as LLM tools.

  5. The fork-and-evaluate pattern. A single live chain read seeds N independent in-memory twins under distinct price-shock scenarios, evaluated in sub-second wall-clock time.

Main Findings

  • The reactive bottleneck is a software choice, not a mathematical necessity. Because the transition map f is a pure function of state and input with no hidden randomness on the protocol side, an off-chain replica pinned to a block is sufficient for any analytical workflow that does not require canonical on-chain settlement.

  • Per-step and cumulative fidelity bounds are stated. Under floor-rounded fixed-point arithmetic, the constant-product invariant satisfies K − r_0^{(k+1)} ≤ K′ ≤ K, giving |K′ − K| ≤ r_0^{(k+1)} per swap and |K_n − K_0| ≤ nB over n swaps with reserve bound B.

  • The worst-case bound is loose in practice. For mainnet pools with reserves on the order of 10^18 to 10^24 minimal token units and n on the order of tens of swaps, the relative slack nB/K_0 is on the order of 10^-10 or smaller — described as "economically exact" on realistic instances even where only provably ε-close in the worst case.

  • Forking is what on-chain state cannot do. Property T4 (clone) yields an independent twin whose evolution does not back-propagate to the original; an on-chain pool admits exactly one trajectory per epoch, while a State Twin admits arbitrarily many. The paper notes that forking on-chain under hypotheticals would require either N real transactions (impossible for hypotheticals) or N RPC reads at N hypothetical blocks (which do not exist).

  • Performance signature: N scenarios at the cost of 1 chain read. In the v2.1 reference demo against the USDC/WETH 5bps Uniswap V3 mainnet pool, N = 50 scenarios complete in well under one second of wall-clock time after the initial chain read; the dominant cost is the single RPC round trip, with each additional fork "essentially free" modulo deepcopy on a small typed object.

  • V3 linearizes to V2 at the active tick. For active-liquidity primitives, the V3 transition is structurally identical to V2 with the discretized rule applied to virtual reserves, and the rounding bound applies verbatim — which is why V3 exposes the same primitive surface as V2 against the twin.

  • One primitive serves three audiences unchanged. The same AnalyzePosition().apply(lp, …) call serves a notebook quant against a synthetic twin, a backtest against a LiveProvider twin pinned to a historical block, and an LLM agent via the MCP server — no per-audience adapter, no agent-specific path.

  • An anecdotal live LLM test is reported. A Claude Desktop session asked "check the health of the eth_dai_v2 pool"; the MCP server dispatched CheckPoolHealth against a MockProvider twin, returned the typed result, and the LLM inferred the pool's state and proactively suggested DetectRugSignals without any explicit composition primitive. The paper states this was verified live before the v2 release but reports no systematic evaluation of it.

  • The paper ships substrate, not an agent. The math layer is deliberately kept deterministic, dependency-light, and LLM-free; the agentic surface is deliberately read-only; LLM integration is a thin adapter at the agent layer.

Methodology in Plain English

Moore's approach is to stop treating a DeFi pool as a thing you have to ask the blockchain about, and start treating it as a small deterministic machine you can copy into memory. The argument unfolds in three moves.

First, he writes each AMM family down in the standard control-theory notation where a system has a state, an input, and an observation, and where the next state is a pure function of the current state plus the input. Because the transition function is fully known and has no randomness, nothing is lost mathematically by running it locally — the only thing the chain contributes beyond state is settlement.

Second, he defines what a faithful in-memory copy must satisfy: it must match the chain's state structure, produce the same observables, evolve the same way under the same inputs, and be clonable into independent copies. The one place the copy can drift is integer rounding in deployed fixed-point arithmetic, so he borrows a per-swap rounding bound from prior work and telescopes it across many swaps to get a cumulative worst-case error of n times the reserve bound. He then checks the magnitude on realistic pool sizes and finds the relative error is around 10^-10 or smaller.

Third, he shows the engineering shape that makes this reusable: split the problem into a provider that knows where state comes from (a synthetic recipe, a live RPC call, a CSV file) and a builder that knows what shape the state has (which protocol family and invariant). The snapshot dataclass is the hand-off between them. Because these two axes vary independently, adding a new data source or a new protocol costs one adapter each rather than a full cross-product. Analytical primitives then consume only the built twin, so they cannot tell whether the input came from a mock or mainnet. The toolkit, DeFiPy v2, is the working demonstration, and the fork-and-evaluate example — one chain read, then N scenario copies — is the payoff workflow.

Why This Matters

Impact on research. The paper reframes a widely observed engineering annoyance (agents can't afford to "think before acting" on chain) as a structural gap in the stack, and supplies a named abstraction plus a stated error bound to fill it. It also bridges two normally separate literatures — AMM protocol mathematics and state-space control theory — and positions its deterministic specialization explicitly against adjacent formalisms: stochastic state-space for adaptive mechanism design, constant-function characterization, priced timed automata for verification, and dependently-typed functional transitions for theorem proving. Treating the twin as a substrate rather than a product also gives follow-on work (ensembles, Monte Carlo, backtesting) a common object to build on.

Real-world applications:

  • Pre-trade risk simulation. A trader or treasury agent evaluates a grid of price shocks against a pinned live pool state before committing capital, rather than submitting transactions to discover outcomes.
  • LLM tool-use in DeFi. An assistant answers "what happens to my LP position if ETH drops 20 percent" by forking a twin locally, instead of issuing RPC calls per hypothesis.
  • Backtesting and strategy research. Pinning a provider to a historical block turns the same primitives into a backtest harness with no new infrastructure.
  • Depeg and pool-health monitoring. Stableswap primitives invert the closed-form relationship between depeg magnitude and LP value loss to produce risk metrics with no chain dependency at evaluation time.
  • Agent ensembles. Multiple agents each operate on their own fork with distinct scenario policies, aggregated by voting, stacking, or Bayesian averaging — a workflow the paper states reactive architectures cannot host at all.

Industry relevance. The design choices are explicitly positioned for durability: three install profiles (defipy, defipy[chain], defipy[agentic]) keep web3 and LLM dependencies out of the core math, the MCP server is a thin adapter over a stable primitive interface, and the authors compare the substrate/product separation to ethers.js and web3.py — libraries whose value is that they do not opine on what the consumer builds. For teams currently hard-wiring models to RPC endpoints, the paper is a direct architectural counter-proposal.

Future Directions

  • Stochastic generalization. Promote u_k and w_k to random variables so the substrate hosts Monte Carlo, filtering, or Bayesian primitives over the deterministic twin, producing a distribution over outcomes rather than a point estimate. The paper names this as forthcoming work that composes with stochastic state-space treatments of AMMs.

  • Multi-agent ensemble reasoning. Spawn N independent agents on N forks with distinct scenario-generation policies and objective functions, aggregating by ensemble methods. The paper flags property T4 as exactly the structural independence condition ensemble theory requires, and treats this as a separate forthcoming paper.

  • Tighter fidelity bounds under structural assumptions. The nB bound is worst-case and loose in practice; the paper identifies bounded swap size relative to reserves, specific arithmetic-mode choices, and distributional assumptions on the swap sequence as routes to tighter results.

  • Full characterization of the substrate necessity argument. The corollary to Remark 1 — that any architecture supporting counterfactual queries must contain a local state realization independent of the chain-read map — is explicitly "sketched," with the full development deferred to later work.

  • LLM-driven scenario design and sequential multi-block reasoning. Letting the agent propose its own scenarios as tool inputs, and chaining forks across blocks to evaluate multi-step strategies without on-chain settlement, are both described as natural extensions of the pattern.

Target Audience

Most valuable to: Protocol engineers and quantitative developers building DeFi analytics or trading infrastructure; AI/agent-system engineers wiring LLMs to on-chain data who need to understand why direct RPC coupling limits what an agent can do; and researchers working on formal or verified models of AMM behaviour who want a practical, shipping counterpart to verification-oriented formalisms.

Also relevant to: Technical product leads deciding where to draw the line between agent framework and underlying library; auditors and risk analysts interested in reproducible, block-pinned state reconstruction; and graduate students in distributed systems or control theory looking for a clean applied example of state-space modelling outside its home discipline.

Less suited to: Readers seeking empirical benchmarking of agent decision quality, systematic evaluation of LLM tool-use accuracy, gas or latency comparisons against production RPC stacks, or protocol-security analysis — the paper reports a single anecdotal live LLM session, one demo timing (N = 50 scenarios in well under one second after the initial read), and no head-to-head benchmark against reactive baselines.

Authors’ abstract

We introduce the State Twin: a typed, in-memory, replayable replica of an on-chain automated market maker (AMM) pool that serves as a substrate for agentic reasoning over decentralized finance (DeFi) protocols. Agentic DeFi stacks today couple reasoning to chain time, since every "what if?" query incurs a new RPC read or a real transaction, so the agent's effective action space is bounded by block confirmation latency and gas. We argue this coupling is a structural problem…

The full abstract on arXiv
Read the original paper