DeFiPy 1.2.0__tar.gz → 2.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 (125) hide show
  1. defipy-2.1.0/DeFiPy.egg-info/PKG-INFO +350 -0
  2. defipy-2.1.0/DeFiPy.egg-info/SOURCES.txt +115 -0
  3. defipy-2.1.0/DeFiPy.egg-info/requires.txt +30 -0
  4. defipy-2.1.0/PKG-INFO +350 -0
  5. defipy-2.1.0/README.md +303 -0
  6. {defipy-1.2.0 → defipy-2.1.0}/python/prod/__init__.py +11 -12
  7. defipy-2.1.0/python/prod/primitives/__init__.py +7 -0
  8. defipy-2.1.0/python/prod/primitives/comparison/CompareFeeTiers.py +319 -0
  9. defipy-2.1.0/python/prod/primitives/comparison/CompareProtocols.py +659 -0
  10. defipy-2.1.0/python/prod/primitives/comparison/__init__.py +2 -0
  11. defipy-2.1.0/python/prod/primitives/execution/CalculateSlippage.py +224 -0
  12. defipy-2.1.0/python/prod/primitives/execution/DetectMEV.py +226 -0
  13. defipy-2.1.0/python/prod/primitives/execution/__init__.py +2 -0
  14. defipy-2.1.0/python/prod/primitives/optimization/EvaluateRebalance.py +401 -0
  15. defipy-2.1.0/python/prod/primitives/optimization/EvaluateTickRanges.py +357 -0
  16. defipy-2.1.0/python/prod/primitives/optimization/OptimalDepositSplit.py +272 -0
  17. defipy-2.1.0/python/prod/primitives/optimization/__init__.py +3 -0
  18. defipy-2.1.0/python/prod/primitives/pool_health/CheckPoolHealth.py +246 -0
  19. defipy-2.1.0/python/prod/primitives/pool_health/DetectFeeAnomaly.py +274 -0
  20. defipy-2.1.0/python/prod/primitives/pool_health/DetectRugSignals.py +230 -0
  21. defipy-2.1.0/python/prod/primitives/pool_health/__init__.py +3 -0
  22. defipy-2.1.0/python/prod/primitives/portfolio/AggregatePortfolio.py +431 -0
  23. defipy-2.1.0/python/prod/primitives/portfolio/__init__.py +1 -0
  24. defipy-2.1.0/python/prod/primitives/position/AnalyzeBalancerPosition.py +247 -0
  25. {defipy-1.2.0 → defipy-2.1.0}/python/prod/primitives/position/AnalyzePosition.py +15 -16
  26. defipy-2.1.0/python/prod/primitives/position/AnalyzeStableswapPosition.py +311 -0
  27. defipy-2.1.0/python/prod/primitives/position/FindBreakEvenPrice.py +182 -0
  28. defipy-2.1.0/python/prod/primitives/position/FindBreakEvenTime.py +250 -0
  29. defipy-2.1.0/python/prod/primitives/position/SimulateBalancerPriceMove.py +201 -0
  30. defipy-2.1.0/python/prod/primitives/position/SimulatePriceMove.py +177 -0
  31. defipy-2.1.0/python/prod/primitives/position/SimulateStableswapPriceMove.py +237 -0
  32. defipy-2.1.0/python/prod/primitives/position/__init__.py +8 -0
  33. defipy-2.1.0/python/prod/primitives/risk/AssessDepegRisk.py +239 -0
  34. defipy-2.1.0/python/prod/primitives/risk/CheckTickRangeStatus.py +154 -0
  35. defipy-2.1.0/python/prod/primitives/risk/__init__.py +2 -0
  36. defipy-2.1.0/python/prod/tools/__init__.py +4 -0
  37. defipy-2.1.0/python/prod/tools/registry.py +397 -0
  38. defipy-2.1.0/python/prod/tools/schemas.py +54 -0
  39. defipy-2.1.0/python/prod/twin/__init__.py +23 -0
  40. defipy-2.1.0/python/prod/twin/_rpc.py +315 -0
  41. defipy-2.1.0/python/prod/twin/builder.py +159 -0
  42. defipy-2.1.0/python/prod/twin/live_provider.py +487 -0
  43. defipy-2.1.0/python/prod/twin/mock_provider.py +97 -0
  44. defipy-2.1.0/python/prod/twin/provider.py +53 -0
  45. defipy-2.1.0/python/prod/twin/snapshot.py +163 -0
  46. defipy-2.1.0/python/prod/utils/data/BalancerPositionAnalysis.py +104 -0
  47. defipy-2.1.0/python/prod/utils/data/BalancerPriceMoveScenario.py +73 -0
  48. defipy-2.1.0/python/prod/utils/data/BreakEvenAlphas.py +88 -0
  49. defipy-2.1.0/python/prod/utils/data/BreakEvenTime.py +100 -0
  50. defipy-2.1.0/python/prod/utils/data/DepegRiskAssessment.py +138 -0
  51. defipy-2.1.0/python/prod/utils/data/DepositSplitResult.py +85 -0
  52. defipy-2.1.0/python/prod/utils/data/FeeAnomalyResult.py +115 -0
  53. defipy-2.1.0/python/prod/utils/data/FeeTierCandidate.py +56 -0
  54. defipy-2.1.0/python/prod/utils/data/FeeTierComparison.py +114 -0
  55. defipy-2.1.0/python/prod/utils/data/MEVDetectionResult.py +101 -0
  56. defipy-2.1.0/python/prod/utils/data/PoolHealth.py +108 -0
  57. defipy-2.1.0/python/prod/utils/data/PortfolioAnalysis.py +133 -0
  58. defipy-2.1.0/python/prod/utils/data/PortfolioPosition.py +85 -0
  59. defipy-2.1.0/python/prod/utils/data/PriceMoveScenario.py +52 -0
  60. defipy-2.1.0/python/prod/utils/data/ProtocolComparison.py +120 -0
  61. defipy-2.1.0/python/prod/utils/data/RebalanceCostReport.py +115 -0
  62. defipy-2.1.0/python/prod/utils/data/RugSignalReport.py +73 -0
  63. defipy-2.1.0/python/prod/utils/data/SlippageAnalysis.py +64 -0
  64. defipy-2.1.0/python/prod/utils/data/StableswapPositionAnalysis.py +110 -0
  65. defipy-2.1.0/python/prod/utils/data/StableswapPriceMoveScenario.py +83 -0
  66. defipy-2.1.0/python/prod/utils/data/TickRangeCandidate.py +48 -0
  67. defipy-2.1.0/python/prod/utils/data/TickRangeEvaluation.py +128 -0
  68. defipy-2.1.0/python/prod/utils/data/TickRangeStatus.py +61 -0
  69. defipy-2.1.0/python/prod/utils/data/__init__.py +27 -0
  70. defipy-2.1.0/setup.py +109 -0
  71. defipy-1.2.0/DeFiPy.egg-info/PKG-INFO +0 -167
  72. defipy-1.2.0/DeFiPy.egg-info/SOURCES.txt +0 -56
  73. defipy-1.2.0/DeFiPy.egg-info/requires.txt +0 -16
  74. defipy-1.2.0/PKG-INFO +0 -167
  75. defipy-1.2.0/README.md +0 -130
  76. defipy-1.2.0/python/prod/primitives/__init__.py +0 -1
  77. defipy-1.2.0/python/prod/primitives/position/__init__.py +0 -1
  78. defipy-1.2.0/python/prod/utils/data/__init__.py +0 -4
  79. defipy-1.2.0/setup.py +0 -73
  80. {defipy-1.2.0 → defipy-2.1.0}/DeFiPy.egg-info/dependency_links.txt +0 -0
  81. {defipy-1.2.0 → defipy-2.1.0}/DeFiPy.egg-info/not-zip-safe +0 -0
  82. {defipy-1.2.0 → defipy-2.1.0}/DeFiPy.egg-info/top_level.txt +0 -0
  83. {defipy-1.2.0 → defipy-2.1.0}/LICENSE +0 -0
  84. {defipy-1.2.0 → defipy-2.1.0}/NOTICE +0 -0
  85. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/ImpermanentLossAgent.py +0 -0
  86. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/PriceThresholdSwapAgent.py +0 -0
  87. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/TVLBasedLiquidityExitAgent.py +0 -0
  88. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/VolumeSpikeNotifierAgent.py +0 -0
  89. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/__init__.py +0 -0
  90. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/config/ImpermanentLossConfig.py +0 -0
  91. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/config/PriceThresholdConfig.py +0 -0
  92. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/config/TVLExitConfig.py +0 -0
  93. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/config/VolumeSpikeConfig.py +0 -0
  94. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/config/__init__.py +0 -0
  95. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/data/UniswapPoolData.py +0 -0
  96. {defipy-1.2.0 → defipy-2.1.0}/python/prod/agents/data/__init__.py +0 -0
  97. {defipy-1.2.0 → defipy-2.1.0}/python/prod/analytics/risk/__init__.py +0 -0
  98. {defipy-1.2.0 → defipy-2.1.0}/python/prod/analytics/simulate/__init__.py +0 -0
  99. {defipy-1.2.0 → defipy-2.1.0}/python/prod/erc/__init__.py +0 -0
  100. {defipy-1.2.0 → defipy-2.1.0}/python/prod/math/basic/__init__.py +0 -0
  101. {defipy-1.2.0 → defipy-2.1.0}/python/prod/math/interest/__init__.py +0 -0
  102. {defipy-1.2.0 → defipy-2.1.0}/python/prod/math/interest/ips/__init__.py +0 -0
  103. {defipy-1.2.0 → defipy-2.1.0}/python/prod/math/interest/ips/aggregate/__init__.py +0 -0
  104. {defipy-1.2.0 → defipy-2.1.0}/python/prod/math/model/__init__.py +0 -0
  105. {defipy-1.2.0 → defipy-2.1.0}/python/prod/math/risk/__init__.py +0 -0
  106. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/__init__.py +0 -0
  107. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/burn/__init__.py +0 -0
  108. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/deposit/__init__.py +0 -0
  109. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/join/Join.py +0 -0
  110. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/join/__init__.py +0 -0
  111. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/liquidity/AddLiquidity.py +0 -0
  112. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/liquidity/RemoveLiquidity.py +0 -0
  113. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/liquidity/__init__.py +0 -0
  114. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/mint/__init__.py +0 -0
  115. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/swap/Swap.py +0 -0
  116. {defipy-1.2.0 → defipy-2.1.0}/python/prod/process/swap/__init__.py +0 -0
  117. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/client/__init__.py +0 -0
  118. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/client/contract/ExecuteScript.py +0 -0
  119. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/client/contract/__init__.py +0 -0
  120. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/data/PositionAnalysis.py +0 -0
  121. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/interfaces/__init__.py +0 -0
  122. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/tools/UniswapScriptHelper.py +0 -0
  123. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/tools/__init__.py +0 -0
  124. {defipy-1.2.0 → defipy-2.1.0}/python/prod/utils/tools/v3/__init__.py +0 -0
  125. {defipy-1.2.0 → defipy-2.1.0}/setup.cfg +0 -0
@@ -0,0 +1,350 @@
1
+ Metadata-Version: 2.4
2
+ Name: DeFiPy
3
+ Version: 2.1.0
4
+ Summary: Python SDK for Agentic DeFi
5
+ Home-page: http://github.com/defipy-devs/defipy
6
+ Author: icmoore
7
+ Author-email: defipy.devs@gmail.com
8
+ License: Apache-2.0
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Requires-Dist: scipy>=1.7.3
13
+ Requires-Dist: numpy>=1.21
14
+ Requires-Dist: gmpy2>=2.1
15
+ Requires-Dist: pandas>=1.3
16
+ Requires-Dist: pydantic>=2.11.0
17
+ Requires-Dist: attrs>=21.0
18
+ Requires-Dist: termcolor>=2.4.0
19
+ Requires-Dist: bokeh>=3.3
20
+ Requires-Dist: uniswappy>=1.7.9
21
+ Requires-Dist: balancerpy>=1.1.0
22
+ Requires-Dist: stableswappy>=1.1.0
23
+ Provides-Extra: chain
24
+ Requires-Dist: web3scout>=0.2.0; extra == "chain"
25
+ Requires-Dist: web3<7.0,>=6.0; extra == "chain"
26
+ Provides-Extra: book
27
+ Requires-Dist: web3scout>=0.2.0; extra == "book"
28
+ Requires-Dist: web3<7.0,>=6.0; extra == "book"
29
+ Provides-Extra: anvil
30
+ Requires-Dist: web3<7.0,>=6.0; extra == "anvil"
31
+ Provides-Extra: mcp
32
+ Requires-Dist: mcp>=1.27.0; extra == "mcp"
33
+ Provides-Extra: agentic
34
+ Requires-Dist: web3scout>=0.2.0; extra == "agentic"
35
+ Requires-Dist: web3<7.0,>=6.0; extra == "agentic"
36
+ Requires-Dist: mcp>=1.27.0; extra == "agentic"
37
+ Dynamic: author
38
+ Dynamic: author-email
39
+ Dynamic: description
40
+ Dynamic: description-content-type
41
+ Dynamic: home-page
42
+ Dynamic: license
43
+ Dynamic: license-file
44
+ Dynamic: provides-extra
45
+ Dynamic: requires-dist
46
+ Dynamic: summary
47
+
48
+ # DeFiPy: Python SDK for Agentic DeFi
49
+
50
+ DeFiPy is the Python SDK for agentic DeFi — a substrate of composable, typed primitives built on hand-derived AMM math across four families (Uniswap V2, Uniswap V3, Balancer, and Curve-style Stableswap). Most DeFi tools wrap APIs; DeFiPy ships the math. Whether you're building dashboards, simulations, notebook research, or agent-based systems, the primitives compose the same way: stateless construction, exact computation at `.apply()`, structured dataclass results.
51
+
52
+ Underneath, DeFiPy is modular by protocol:
53
+
54
+ * [UniswapPy](https://github.com/defipy-devs/uniswappy)
55
+ * [BalancerPy](https://github.com/defipy-devs/balancerpy)
56
+ * [StableSwapPy](https://github.com/defipy-devs/stableswappy)
57
+
58
+ For onchain event access and scripting, use [LiveProvider](https://defipy.org/live-provider/) as of v2.1 — it pulls live pool state into the same primitive surface that runs against synthetic recipes. Under the hood it's powered by [Web3Scout](https://github.com/defipy-devs/web3scout); install via the `[chain]` extra (see below).
59
+
60
+ 🔗 SPDX-Anchor: [anchorregistry.ai/AR-2026-YdPXB5g](https://anchorregistry.ai/AR-2026-YdPXB5g)
61
+
62
+ ## 🆕 What's new in v2.1
63
+
64
+ v2.1 makes the [State Twin](https://defipy.org/twin-concept/) **real**. `LiveProvider` ships for Uniswap V2 and V3 — chain reads compose with every primitive in the library, the same way `MockProvider` recipes do. The "what would happen if?" loop is now local: pull state once, simulate forever, decide before executing.
65
+
66
+ * **`LiveProvider`** — `provider.snapshot("uniswap_v2:0xADDR")` and `provider.snapshot("uniswap_v3:0xADDR")` build `V2PoolSnapshot` and `V3PoolSnapshot` from real on-chain state. Block pinning is automatic — `"latest"` resolves once at the top of `.snapshot()` and every read inside that snapshot pins to the same block. Pass `block_number=N` for historical reads.
67
+ * **Multicall3 batching for V3** — V3 snapshots batch `slot0`, `liquidity`, `fee`, `tickSpacing`, `token0`, `token1`, and block timestamp into one [Multicall3](https://github.com/mds1/multicall) `aggregate3` round trip. Hardcoded canonical Multicall3 address; works on every major EVM chain.
68
+ * **`PoolSnapshot` enrichment** — every snapshot now carries `block_number`, `timestamp`, `chain_id` as optional fields. `LiveProvider` populates them from chain reads; `MockProvider` leaves them `None` to honestly signal "synthetic, not chain state."
69
+ * **`PoolHealth` ergonomics for V3** — `CheckPoolHealth` now reports `fee_pips` (V3 fee tier in pips, `None` for V2), `tvl_in_token1` (symmetric to existing `tvl_in_token0`), and `tick_current` (V3 current tick, `None` for V2). All additive; no API breakage. `RugSignalReport` gets the new fields transitively.
70
+ * **`provider.get_w3()`** — the underlying `web3.Web3` instance is now public, for callers who want to sign transactions or wire LiveProvider into their own broader chain tooling. DeFiPy stays read-only by design; bring your own signing opinion.
71
+ * **Fork-and-evaluate worked example** — [`python/examples/state_twin_fork_evaluate.py`](./python/examples/state_twin_fork_evaluate.py) demonstrates the State Twin's multi-scenario reasoning pattern against live mainnet state. Pull a V3 pool snapshot once, fork the twin N ways under price scenarios, run primitives against each fork, aggregate into a recommendation. Walks through the pattern at [defipy.org/fork-evaluate/](https://defipy.org/fork-evaluate/).
72
+ * **`[chain]` install extra** — `pip install defipy[chain]` adds `web3scout` and `web3.py` for users who want LiveProvider. Core install (no extras) remains free of any chain or LLM dependencies.
73
+ * **`[agentic]` install extra** — `pip install defipy[agentic]` composes `[chain]` and `[mcp]` for the canonical *Python SDK for Agentic DeFi* full-stack install. Equivalent to `pip install defipy[chain,mcp]` but spelled with intent.
74
+
75
+ V2.1 is a strict superset of v2.0 — every v2.0 primitive, MockProvider recipe, and MCP server pattern works identically. What changes is that the same primitives now run against live chain state without changing call shape.
76
+
77
+ **What's deferred to v2.2:** Balancer and Stableswap LiveProvider implementations raise `NotImplementedError` pointing at the planned version. V3 tick bitmap walking is also v2.2 work; in v2.1, V3 LiveProvider snapshots cover active-liquidity only — primitives that depend on non-active-tick liquidity (e.g., `AssessLiquidityDepth`) ship in v2.2.
78
+
79
+ ## v2.0 foundations
80
+
81
+ The State Twin abstraction, agentic primitives, and MCP server pattern shipped in v2.0. v2.1 builds on that surface without changing it:
82
+
83
+ * **`defipy.tools`** — self-describing schemas for a curated set of 10 leaf primitives, in [Model Context Protocol](https://modelcontextprotocol.io) (MCP) format. Any MCP-compatible client can discover and invoke DeFiPy primitives as tools.
84
+ * **`defipy.twin`** — the **State Twin** abstraction. `MockProvider` ships four canonical synthetic pools (V2, V3, Balancer, Stableswap) for notebooks and tests; `LiveProvider` ships chain reads for V2 and V3 in v2.1.
85
+ * **MCP server demo** at [`python/mcp/`](./python/mcp/) — a stdio-transport server exposing DeFiPy's tools to Claude Desktop, Claude Code, or any MCP client. Install with `pip install defipy[mcp]` and see the [MCP server README](./python/mcp/README.md) for setup.
86
+
87
+ ### What is MCP?
88
+
89
+ The [Model Context Protocol](https://modelcontextprotocol.io) is an open standard for giving LLMs access to tools and data. With DeFiPy's MCP server running, Claude can answer natural-language LP questions backed by exact math:
90
+
91
+ > *"Is this V2 pool healthy? Any rug signals?"*
92
+
93
+ Claude reads the tool descriptions, picks `CheckPoolHealth`, calls it against a twin (synthetic via MockProvider, or live via LiveProvider), receives the typed dataclass result, and synthesizes a response — one that correctly interprets TVL, LP concentration, and activity signals, because the primitives encode the domain, not the LLM.
94
+
95
+ **Substrate, not agent.** DeFiPy itself has zero LLM dependencies and zero network calls at core. The library is a substrate that agent runtimes (including forthcoming DeFiMind and any third-party project) build on top of.
96
+
97
+ ## 🧩 What DeFiPy offers
98
+
99
+ **7 [Core primitives](https://defipy.org/core-primitives/)** for cross-protocol pool execution — `Join`, `Swap`, `AddLiquidity`, `RemoveLiquidity`, `SwapDeposit`, `WithdrawSwap`, `LPQuote`. State-mutating operations that work across Uniswap V2/V3, Balancer, and Stableswap through a single abstract interface.
100
+
101
+ **21 [Agentic primitives](https://defipy.org/agentic-primitives/)** across 7 categories. Each answers a specific LP question with exact math and returns a typed dataclass result:
102
+
103
+ * **Position analysis** — "Why is my position losing money? What if price moves X%?" PnL decomposition (IL, fees, net result) and price-move scenarios across Uniswap V2/V3, Balancer, and Stableswap. Includes break-even pricing and time-to-breakeven analysis.
104
+ * **Pool health** — "Is this pool healthy? Any rug signals?" TVL, LP concentration, activity, threshold-based rug detection, fee-anomaly checks (V2/V3).
105
+ * **Risk** — "How exposed am I to a stablecoin depeg? Is my V3 range safe?" Stableswap IL at multiple depeg levels with V2 comparison baseline; V3 tick-range status.
106
+ * **Execution** — "What's my actual slippage? Maximum trade size before it exceeds X%? Did a swap get MEV'd?" (V2/V3).
107
+ * **Optimization** — Zap-in optimal swap fractions, V3 tick range evaluation, rebalance cost analysis.
108
+ * **Comparison** — Side-by-side same-capital analysis across protocols or V3 fee tiers.
109
+ * **Portfolio** — Multi-position aggregation with cross-protocol dispatch.
110
+
111
+ Full primitive catalog with LP-question mappings lives in the [v2 docs](https://defipy.org).
112
+
113
+ *Legacy event-driven agents (`python/prod/agents/`) are preserved for chapter 9 of* Hands-On AMMs with Python *but are not the go-forward architecture — new agentic behavior composes from primitives running against State Twin twins.*
114
+
115
+ ## 📝 Docs
116
+ Visit [**DeFiPy docs**](https://defipy.org) for full documentation. The [LiveProvider page](https://defipy.org/live-provider/) covers the v2.1 chain-reading surface in detail.
117
+
118
+ ## 🔍 Install
119
+
120
+ DeFiPy requires **Python 3.10 or later**. Install via pip:
121
+
122
+ ```
123
+ > pip install defipy
124
+ ```
125
+
126
+ The core install is the pure analytics engine — AMM math, primitives, State Twin, and all 21 typed analytics functions. It has **zero web3 dependencies and zero LLM dependencies**. No chain reads, no RPC calls, no MCP. Chain reads come from [Web3Scout](https://github.com/defipy-devs/web3scout) (via the `[chain]` or `[book]` extras); MCP tool serving comes from the `[mcp]` extra. All optional.
127
+
128
+ ### Chain install (LiveProvider — v2.1+)
129
+
130
+ To use `LiveProvider` for on-chain pool snapshots, install the `[chain]` extra:
131
+
132
+ ```
133
+ > pip install defipy[chain]
134
+ ```
135
+
136
+ This pulls in `web3scout` (which `LiveProvider` uses internally for ABI loading, contract reads, and token-fetching) plus `web3.py`. With `[chain]` installed, you can construct twins from real chain state:
137
+
138
+ ```python
139
+ from defipy.twin import LiveProvider, StateTwinBuilder
140
+
141
+ provider = LiveProvider("https://eth-mainnet.g.alchemy.com/v2/<key>")
142
+ snapshot = provider.snapshot("uniswap_v2:0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc")
143
+ lp = StateTwinBuilder().build(snapshot)
144
+ ```
145
+
146
+ > **Note:** the `[chain]` extra pins `web3 < 7.0` because `web3scout 0.2.0` depends on `eth_utils.abi.get_abi_input_types`, which was removed in web3 7. If you have web3 7.x installed for other reasons, `pip install defipy[chain]` will downgrade it. Tracking upstream as v2.2 work.
147
+
148
+ ### Agentic install (full LLM + chain stack)
149
+
150
+ For users building LLM-driven systems against live chain state — the canonical *Python SDK for Agentic DeFi* use case — install the `[agentic]` extra:
151
+
152
+ ```
153
+ > pip install defipy[agentic]
154
+ ```
155
+
156
+ This composes `[chain]` and `[mcp]` in one step: `web3scout` and `web3.py` for `LiveProvider` chain reads, plus the `mcp` Python SDK for serving DeFiPy's primitives as tools to Claude Desktop, Claude Code, or any MCP-compatible client. Equivalent to `pip install defipy[chain,mcp]` but spelled with intent.
157
+
158
+ The same `web3 < 7.0` pin from the `[chain]` extra applies.
159
+
160
+ ### MCP install (Claude Desktop / Claude Code demo)
161
+
162
+ To run the MCP server that exposes DeFiPy's primitives as tools to Claude Desktop, Claude Code, or any MCP-compatible client, install the `[mcp]` extra:
163
+
164
+ ```
165
+ > pip install defipy[mcp]
166
+ ```
167
+
168
+ This adds the [`mcp`](https://github.com/modelcontextprotocol/python-sdk) Python SDK on top of the core install. The MCP server itself lives at [`python/mcp/defipy_mcp_server.py`](./python/mcp/defipy_mcp_server.py); see [`python/mcp/README.md`](./python/mcp/README.md) for Claude Desktop and Claude Code configuration snippets.
169
+
170
+ ### Book install (chapter 9 agents)
171
+
172
+ Chapter 9 of *Hands-On AMMs with Python* — *Building Autonomous DeFi Agents* — uses live chain integration via `web3scout`. To run those examples, install the `[book]` extra:
173
+
174
+ ```
175
+ > pip install defipy[book]
176
+ ```
177
+
178
+ The `[book]` extra carries the same package set as `[chain]` (`web3scout` + `web3`). The split is intent-based — `[chain]` signals production live-state reads via LiveProvider; `[book]` signals textbook chapter 9 use. Either works for either purpose.
179
+
180
+ ### Anvil install (local Foundry workflows)
181
+
182
+ If you're using `ExecuteScript` or `UniswapScriptHelper` against a local [Anvil](https://book.getfoundry.sh/anvil/) node and don't need the full `web3scout` event-monitoring stack, the lighter `[anvil]` extra just adds `web3.py`:
183
+
184
+ ```
185
+ > pip install defipy[anvil]
186
+ ```
187
+
188
+ `[book]` and `[chain]` already include everything in `[anvil]`, so users on either of those don't need it separately.
189
+
190
+ ### Source install
191
+
192
+ To install from source:
193
+
194
+ ```
195
+ > git clone https://github.com/defipy-devs/defipy
196
+ > cd defipy
197
+ > pip install .
198
+ ```
199
+
200
+ ### System libraries for gmpy2
201
+
202
+ DeFiPy depends on `gmpy2` for high-precision arithmetic in StableSwap math. On most platforms, `pip` will install `gmpy2` from a prebuilt wheel and no further setup is needed. If the install fails, you may need the GMP, MPFR, and MPC system libraries installed *before* `pip install`:
203
+
204
+ **macOS (Homebrew):**
205
+ ```
206
+ > brew install gmp mpfr libmpc
207
+ ```
208
+
209
+ **Linux (Debian / Ubuntu):**
210
+ ```
211
+ > sudo apt install libgmp-dev libmpfr-dev libmpc-dev
212
+ ```
213
+
214
+ See the [gmpy2 installation docs](https://gmpy2.readthedocs.io/en/latest/install.html) for other platforms.
215
+
216
+ ## 🔍 Learning Resources
217
+
218
+ DeFiPy is accompanied by educational resources for developers and researchers
219
+ interested in on-chain analytics and DeFi modeling.
220
+
221
+ ### 📘 Textbook
222
+ **_DeFiPy: Python SDK for On-Chain Analytics_**
223
+
224
+ A comprehensive guide to DeFi analytics, AMM modeling, and simulation.
225
+
226
+ 🔗 **Buy on Amazon:** https://www.amazon.com/dp/B0G3RV5QRB
227
+
228
+ ### 🎓 Course
229
+ **On-Chain Analytics Foundations**
230
+
231
+ A practical course on transforming raw blockchain data into structured
232
+ analytics pipelines using Python.
233
+
234
+ Topics include:
235
+
236
+ - retrieving blockchain data via Ethereum RPC
237
+ - decoding event logs
238
+ - analyzing AMM swap events
239
+ - building DeFi analytics pipelines
240
+
241
+ 🔗 **Course Page:** https://defipy.thinkific.com/products/courses/foundations
242
+
243
+ ## 🚀 Quick Example (LiveProvider: real chain state + primitives)
244
+ --------------------------
245
+
246
+ The fastest way to see DeFiPy at work — pull a real Uniswap V2 pool's state from mainnet and run a primitive against it. Requires the `[chain]` install extra.
247
+
248
+ from defipy import AnalyzePosition
249
+ from defipy.twin import LiveProvider, StateTwinBuilder
250
+
251
+ # Pull live state from a real Uniswap V2 pool — WETH/USDC mainnet
252
+ provider = LiveProvider("https://eth-mainnet.g.alchemy.com/v2/<key>")
253
+ snapshot = provider.snapshot(
254
+ "uniswap_v2:0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc"
255
+ )
256
+ lp = StateTwinBuilder().build(snapshot)
257
+ lp.summary()
258
+
259
+ # Snapshot carries chain context — block_number, timestamp, chain_id
260
+ print(f"Block: {snapshot.block_number}")
261
+ print(f"Reserves: {snapshot.token0_name}={snapshot.reserve0:.2f}, "
262
+ f"{snapshot.token1_name}={snapshot.reserve1:.2f}")
263
+
264
+ # Run any primitive against the live twin — same call shape as MockProvider
265
+ result = AnalyzePosition().apply(
266
+ lp,
267
+ lp_init_amt=1.0,
268
+ entry_x_amt=1000,
269
+ entry_y_amt=3_000_000,
270
+ )
271
+
272
+ print(f"Diagnosis: {result.diagnosis}")
273
+ print(f"Net PnL: {result.net_pnl:.4f}")
274
+ print(f"IL %: {result.il_percentage:.4f}")
275
+ print(f"Current val: {result.current_value:.4f}")
276
+
277
+ The same shape works for V3 — swap `uniswap_v2:` for `uniswap_v3:` and the appropriate pool address (e.g. `0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640` for USDC/WETH 500bps). V3 snapshots default to full-range ticks; pass `lwr_tick=N, upr_tick=N` to override. See the [LiveProvider docs](https://defipy.org/live-provider/) for block pinning, the V3 tick-range surface, and the active-liquidity-only caveat.
278
+
279
+ **No chain access?** Substitute `MockProvider` for `LiveProvider` and pass a recipe name (`"eth_dai_v2"`, `"eth_dai_v3"`, `"eth_dai_balancer_50_50"`, `"usdc_dai_stableswap_A10"`). Same primitive call, same result shape, no network needed:
280
+
281
+ from defipy.twin import MockProvider, StateTwinBuilder
282
+
283
+ provider = MockProvider()
284
+ lp = StateTwinBuilder().build(provider.snapshot("eth_dai_v2"))
285
+ # ... AnalyzePosition().apply(lp, ...) works identically
286
+
287
+ The State Twin abstraction is what makes this work: providers know about *sources*, primitives know about *math*, the twin is the canonical handoff between them. Same `lp` shape from a synthetic recipe, a live chain read, or a custom CSV-backed provider — every primitive consumes them identically.
288
+
289
+ For LLM-driven interaction with these primitives, see the [MCP server README](./python/mcp/README.md).
290
+
291
+ ## 🧱 Quick Example (low-level: Uniswap V3 pool construction)
292
+ --------------------------
293
+
294
+ To construct a Uniswap V3 pool directly (outside MockProvider's canonical recipes and outside LiveProvider's chain reads), you must first create the tokens in the pair using the `ERC20` object. Next, create a liquidity pool (LP) factory using `IFactory` object. Once this is setup, an unlimited amount of LPs can be created; the procedures for such are as follows:
295
+
296
+ from defipy import *
297
+
298
+ # Step 1: Define tokens and parameters
299
+ eth = ERC20("ETH", "0x93")
300
+ tkn = ERC20("TKN", "0x111")
301
+ tick_spacing = 60
302
+ fee = 3000 # 0.3% fee tier
303
+
304
+ # Step 2: Set up exchange data for V3
305
+ exch_data = UniswapExchangeData(tkn0=eth, tkn1=tkn, symbol="LP", address="0x811", version='V3', tick_spacing=tick_spacing, fee=fee)
306
+
307
+ # Step 3: Initialize factory
308
+ factory = UniswapFactory("ETH pool factory", "0x2")
309
+
310
+ # Step 4: Deploy pool
311
+ lp = factory.deploy(exch_data)
312
+
313
+ # Step 5: Add initial liquidity within tick range
314
+ lwr_tick = UniV3Utils.getMinTick(tick_spacing)
315
+ upr_tick = UniV3Utils.getMaxTick(tick_spacing)
316
+ join = Join()
317
+ join.apply(lp, "user", 1000, 10000, lwr_tick, upr_tick)
318
+
319
+ # Step 6: Perform swap
320
+ swap = Swap()
321
+ out = swap.apply(lp, tkn, "user", 10)
322
+
323
+ # Check reserves and liquidity
324
+ lp.summary()
325
+
326
+ # OUTPUT:
327
+ Exchange ETH-TKN (LP)
328
+ Real Reserves: ETH = 999.0039930189599, TKN = 10010.0
329
+ Gross Liquidity: 3162.277660168379
330
+
331
+ ## 🧪 Tests
332
+
333
+ DeFiPy ships ~686 tests across primitives, tools, twin, packaging, and the MCP server dispatch layer. Run the full suite:
334
+
335
+ pytest python/test/ -v
336
+
337
+ Expect ~686 passed and 11 skipped — the skipped tests are the live-RPC suites, gated by the `DEFIPY_LIVE_RPC` environment variable. They run against real mainnet pools and aren't part of the default suite to keep CI deterministic.
338
+
339
+ Run just the primitive suite (no MCP or twin dependencies):
340
+
341
+ pytest python/test/primitives/ -v
342
+
343
+ To run the opt-in live-RPC tests, set `DEFIPY_LIVE_RPC` to a mainnet RPC URL:
344
+
345
+ DEFIPY_LIVE_RPC=https://eth-mainnet.g.alchemy.com/v2/<key> pytest -m live_rpc -v
346
+
347
+ ## License
348
+ Licensed under the Apache License, Version 2.0.
349
+ See [LICENSE](./LICENSE) and [NOTICE](./NOTICE) for details.
350
+ Portions of this project may include code from third-party projects under compatible open-source licenses.
@@ -0,0 +1,115 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ setup.cfg
5
+ setup.py
6
+ DeFiPy.egg-info/PKG-INFO
7
+ DeFiPy.egg-info/SOURCES.txt
8
+ DeFiPy.egg-info/dependency_links.txt
9
+ DeFiPy.egg-info/not-zip-safe
10
+ DeFiPy.egg-info/requires.txt
11
+ DeFiPy.egg-info/top_level.txt
12
+ python/prod/__init__.py
13
+ python/prod/agents/ImpermanentLossAgent.py
14
+ python/prod/agents/PriceThresholdSwapAgent.py
15
+ python/prod/agents/TVLBasedLiquidityExitAgent.py
16
+ python/prod/agents/VolumeSpikeNotifierAgent.py
17
+ python/prod/agents/__init__.py
18
+ python/prod/agents/config/ImpermanentLossConfig.py
19
+ python/prod/agents/config/PriceThresholdConfig.py
20
+ python/prod/agents/config/TVLExitConfig.py
21
+ python/prod/agents/config/VolumeSpikeConfig.py
22
+ python/prod/agents/config/__init__.py
23
+ python/prod/agents/data/UniswapPoolData.py
24
+ python/prod/agents/data/__init__.py
25
+ python/prod/analytics/risk/__init__.py
26
+ python/prod/analytics/simulate/__init__.py
27
+ python/prod/erc/__init__.py
28
+ python/prod/math/basic/__init__.py
29
+ python/prod/math/interest/__init__.py
30
+ python/prod/math/interest/ips/__init__.py
31
+ python/prod/math/interest/ips/aggregate/__init__.py
32
+ python/prod/math/model/__init__.py
33
+ python/prod/math/risk/__init__.py
34
+ python/prod/primitives/__init__.py
35
+ python/prod/primitives/comparison/CompareFeeTiers.py
36
+ python/prod/primitives/comparison/CompareProtocols.py
37
+ python/prod/primitives/comparison/__init__.py
38
+ python/prod/primitives/execution/CalculateSlippage.py
39
+ python/prod/primitives/execution/DetectMEV.py
40
+ python/prod/primitives/execution/__init__.py
41
+ python/prod/primitives/optimization/EvaluateRebalance.py
42
+ python/prod/primitives/optimization/EvaluateTickRanges.py
43
+ python/prod/primitives/optimization/OptimalDepositSplit.py
44
+ python/prod/primitives/optimization/__init__.py
45
+ python/prod/primitives/pool_health/CheckPoolHealth.py
46
+ python/prod/primitives/pool_health/DetectFeeAnomaly.py
47
+ python/prod/primitives/pool_health/DetectRugSignals.py
48
+ python/prod/primitives/pool_health/__init__.py
49
+ python/prod/primitives/portfolio/AggregatePortfolio.py
50
+ python/prod/primitives/portfolio/__init__.py
51
+ python/prod/primitives/position/AnalyzeBalancerPosition.py
52
+ python/prod/primitives/position/AnalyzePosition.py
53
+ python/prod/primitives/position/AnalyzeStableswapPosition.py
54
+ python/prod/primitives/position/FindBreakEvenPrice.py
55
+ python/prod/primitives/position/FindBreakEvenTime.py
56
+ python/prod/primitives/position/SimulateBalancerPriceMove.py
57
+ python/prod/primitives/position/SimulatePriceMove.py
58
+ python/prod/primitives/position/SimulateStableswapPriceMove.py
59
+ python/prod/primitives/position/__init__.py
60
+ python/prod/primitives/risk/AssessDepegRisk.py
61
+ python/prod/primitives/risk/CheckTickRangeStatus.py
62
+ python/prod/primitives/risk/__init__.py
63
+ python/prod/process/__init__.py
64
+ python/prod/process/burn/__init__.py
65
+ python/prod/process/deposit/__init__.py
66
+ python/prod/process/join/Join.py
67
+ python/prod/process/join/__init__.py
68
+ python/prod/process/liquidity/AddLiquidity.py
69
+ python/prod/process/liquidity/RemoveLiquidity.py
70
+ python/prod/process/liquidity/__init__.py
71
+ python/prod/process/mint/__init__.py
72
+ python/prod/process/swap/Swap.py
73
+ python/prod/process/swap/__init__.py
74
+ python/prod/tools/__init__.py
75
+ python/prod/tools/registry.py
76
+ python/prod/tools/schemas.py
77
+ python/prod/twin/__init__.py
78
+ python/prod/twin/_rpc.py
79
+ python/prod/twin/builder.py
80
+ python/prod/twin/live_provider.py
81
+ python/prod/twin/mock_provider.py
82
+ python/prod/twin/provider.py
83
+ python/prod/twin/snapshot.py
84
+ python/prod/utils/client/__init__.py
85
+ python/prod/utils/client/contract/ExecuteScript.py
86
+ python/prod/utils/client/contract/__init__.py
87
+ python/prod/utils/data/BalancerPositionAnalysis.py
88
+ python/prod/utils/data/BalancerPriceMoveScenario.py
89
+ python/prod/utils/data/BreakEvenAlphas.py
90
+ python/prod/utils/data/BreakEvenTime.py
91
+ python/prod/utils/data/DepegRiskAssessment.py
92
+ python/prod/utils/data/DepositSplitResult.py
93
+ python/prod/utils/data/FeeAnomalyResult.py
94
+ python/prod/utils/data/FeeTierCandidate.py
95
+ python/prod/utils/data/FeeTierComparison.py
96
+ python/prod/utils/data/MEVDetectionResult.py
97
+ python/prod/utils/data/PoolHealth.py
98
+ python/prod/utils/data/PortfolioAnalysis.py
99
+ python/prod/utils/data/PortfolioPosition.py
100
+ python/prod/utils/data/PositionAnalysis.py
101
+ python/prod/utils/data/PriceMoveScenario.py
102
+ python/prod/utils/data/ProtocolComparison.py
103
+ python/prod/utils/data/RebalanceCostReport.py
104
+ python/prod/utils/data/RugSignalReport.py
105
+ python/prod/utils/data/SlippageAnalysis.py
106
+ python/prod/utils/data/StableswapPositionAnalysis.py
107
+ python/prod/utils/data/StableswapPriceMoveScenario.py
108
+ python/prod/utils/data/TickRangeCandidate.py
109
+ python/prod/utils/data/TickRangeEvaluation.py
110
+ python/prod/utils/data/TickRangeStatus.py
111
+ python/prod/utils/data/__init__.py
112
+ python/prod/utils/interfaces/__init__.py
113
+ python/prod/utils/tools/UniswapScriptHelper.py
114
+ python/prod/utils/tools/__init__.py
115
+ python/prod/utils/tools/v3/__init__.py
@@ -0,0 +1,30 @@
1
+ scipy>=1.7.3
2
+ numpy>=1.21
3
+ gmpy2>=2.1
4
+ pandas>=1.3
5
+ pydantic>=2.11.0
6
+ attrs>=21.0
7
+ termcolor>=2.4.0
8
+ bokeh>=3.3
9
+ uniswappy>=1.7.9
10
+ balancerpy>=1.1.0
11
+ stableswappy>=1.1.0
12
+
13
+ [agentic]
14
+ web3scout>=0.2.0
15
+ web3<7.0,>=6.0
16
+ mcp>=1.27.0
17
+
18
+ [anvil]
19
+ web3<7.0,>=6.0
20
+
21
+ [book]
22
+ web3scout>=0.2.0
23
+ web3<7.0,>=6.0
24
+
25
+ [chain]
26
+ web3scout>=0.2.0
27
+ web3<7.0,>=6.0
28
+
29
+ [mcp]
30
+ mcp>=1.27.0