DeFiPy 1.2.0__tar.gz → 2.0.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.
- defipy-2.0.0/DeFiPy.egg-info/PKG-INFO +266 -0
- defipy-2.0.0/DeFiPy.egg-info/SOURCES.txt +114 -0
- {defipy-1.2.0 → defipy-2.0.0}/DeFiPy.egg-info/requires.txt +10 -5
- defipy-2.0.0/PKG-INFO +266 -0
- defipy-2.0.0/README.md +226 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/__init__.py +11 -12
- defipy-2.0.0/python/prod/primitives/__init__.py +7 -0
- defipy-2.0.0/python/prod/primitives/comparison/CompareFeeTiers.py +319 -0
- defipy-2.0.0/python/prod/primitives/comparison/CompareProtocols.py +659 -0
- defipy-2.0.0/python/prod/primitives/comparison/__init__.py +2 -0
- defipy-2.0.0/python/prod/primitives/execution/CalculateSlippage.py +224 -0
- defipy-2.0.0/python/prod/primitives/execution/DetectMEV.py +226 -0
- defipy-2.0.0/python/prod/primitives/execution/__init__.py +2 -0
- defipy-2.0.0/python/prod/primitives/optimization/EvaluateRebalance.py +401 -0
- defipy-2.0.0/python/prod/primitives/optimization/EvaluateTickRanges.py +357 -0
- defipy-2.0.0/python/prod/primitives/optimization/OptimalDepositSplit.py +272 -0
- defipy-2.0.0/python/prod/primitives/optimization/__init__.py +3 -0
- defipy-2.0.0/python/prod/primitives/pool_health/CheckPoolHealth.py +234 -0
- defipy-2.0.0/python/prod/primitives/pool_health/DetectFeeAnomaly.py +274 -0
- defipy-2.0.0/python/prod/primitives/pool_health/DetectRugSignals.py +230 -0
- defipy-2.0.0/python/prod/primitives/pool_health/__init__.py +3 -0
- defipy-2.0.0/python/prod/primitives/portfolio/AggregatePortfolio.py +431 -0
- defipy-2.0.0/python/prod/primitives/portfolio/__init__.py +1 -0
- defipy-2.0.0/python/prod/primitives/position/AnalyzeBalancerPosition.py +247 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/primitives/position/AnalyzePosition.py +15 -16
- defipy-2.0.0/python/prod/primitives/position/AnalyzeStableswapPosition.py +311 -0
- defipy-2.0.0/python/prod/primitives/position/FindBreakEvenPrice.py +182 -0
- defipy-2.0.0/python/prod/primitives/position/FindBreakEvenTime.py +250 -0
- defipy-2.0.0/python/prod/primitives/position/SimulateBalancerPriceMove.py +201 -0
- defipy-2.0.0/python/prod/primitives/position/SimulatePriceMove.py +177 -0
- defipy-2.0.0/python/prod/primitives/position/SimulateStableswapPriceMove.py +237 -0
- defipy-2.0.0/python/prod/primitives/position/__init__.py +8 -0
- defipy-2.0.0/python/prod/primitives/risk/AssessDepegRisk.py +239 -0
- defipy-2.0.0/python/prod/primitives/risk/CheckTickRangeStatus.py +154 -0
- defipy-2.0.0/python/prod/primitives/risk/__init__.py +2 -0
- defipy-2.0.0/python/prod/tools/__init__.py +4 -0
- defipy-2.0.0/python/prod/tools/registry.py +397 -0
- defipy-2.0.0/python/prod/tools/schemas.py +54 -0
- defipy-2.0.0/python/prod/twin/__init__.py +23 -0
- defipy-2.0.0/python/prod/twin/builder.py +159 -0
- defipy-2.0.0/python/prod/twin/live_provider.py +45 -0
- defipy-2.0.0/python/prod/twin/mock_provider.py +93 -0
- defipy-2.0.0/python/prod/twin/provider.py +42 -0
- defipy-2.0.0/python/prod/twin/snapshot.py +129 -0
- defipy-2.0.0/python/prod/utils/data/BalancerPositionAnalysis.py +104 -0
- defipy-2.0.0/python/prod/utils/data/BalancerPriceMoveScenario.py +73 -0
- defipy-2.0.0/python/prod/utils/data/BreakEvenAlphas.py +88 -0
- defipy-2.0.0/python/prod/utils/data/BreakEvenTime.py +100 -0
- defipy-2.0.0/python/prod/utils/data/DepegRiskAssessment.py +138 -0
- defipy-2.0.0/python/prod/utils/data/DepositSplitResult.py +85 -0
- defipy-2.0.0/python/prod/utils/data/FeeAnomalyResult.py +115 -0
- defipy-2.0.0/python/prod/utils/data/FeeTierCandidate.py +56 -0
- defipy-2.0.0/python/prod/utils/data/FeeTierComparison.py +114 -0
- defipy-2.0.0/python/prod/utils/data/MEVDetectionResult.py +101 -0
- defipy-2.0.0/python/prod/utils/data/PoolHealth.py +89 -0
- defipy-2.0.0/python/prod/utils/data/PortfolioAnalysis.py +133 -0
- defipy-2.0.0/python/prod/utils/data/PortfolioPosition.py +85 -0
- defipy-2.0.0/python/prod/utils/data/PriceMoveScenario.py +52 -0
- defipy-2.0.0/python/prod/utils/data/ProtocolComparison.py +120 -0
- defipy-2.0.0/python/prod/utils/data/RebalanceCostReport.py +115 -0
- defipy-2.0.0/python/prod/utils/data/RugSignalReport.py +73 -0
- defipy-2.0.0/python/prod/utils/data/SlippageAnalysis.py +64 -0
- defipy-2.0.0/python/prod/utils/data/StableswapPositionAnalysis.py +110 -0
- defipy-2.0.0/python/prod/utils/data/StableswapPriceMoveScenario.py +83 -0
- defipy-2.0.0/python/prod/utils/data/TickRangeCandidate.py +48 -0
- defipy-2.0.0/python/prod/utils/data/TickRangeEvaluation.py +128 -0
- defipy-2.0.0/python/prod/utils/data/TickRangeStatus.py +61 -0
- defipy-2.0.0/python/prod/utils/data/__init__.py +27 -0
- {defipy-1.2.0 → defipy-2.0.0}/setup.py +41 -24
- defipy-1.2.0/DeFiPy.egg-info/PKG-INFO +0 -167
- defipy-1.2.0/DeFiPy.egg-info/SOURCES.txt +0 -56
- defipy-1.2.0/PKG-INFO +0 -167
- defipy-1.2.0/README.md +0 -130
- defipy-1.2.0/python/prod/primitives/__init__.py +0 -1
- defipy-1.2.0/python/prod/primitives/position/__init__.py +0 -1
- defipy-1.2.0/python/prod/utils/data/__init__.py +0 -4
- {defipy-1.2.0 → defipy-2.0.0}/DeFiPy.egg-info/dependency_links.txt +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/DeFiPy.egg-info/not-zip-safe +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/DeFiPy.egg-info/top_level.txt +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/LICENSE +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/NOTICE +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/ImpermanentLossAgent.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/PriceThresholdSwapAgent.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/TVLBasedLiquidityExitAgent.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/VolumeSpikeNotifierAgent.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/config/ImpermanentLossConfig.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/config/PriceThresholdConfig.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/config/TVLExitConfig.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/config/VolumeSpikeConfig.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/config/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/data/UniswapPoolData.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/agents/data/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/analytics/risk/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/analytics/simulate/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/erc/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/math/basic/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/math/interest/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/math/interest/ips/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/math/interest/ips/aggregate/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/math/model/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/math/risk/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/burn/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/deposit/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/join/Join.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/join/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/liquidity/AddLiquidity.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/liquidity/RemoveLiquidity.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/liquidity/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/mint/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/swap/Swap.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/process/swap/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/client/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/client/contract/ExecuteScript.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/client/contract/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/data/PositionAnalysis.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/interfaces/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/tools/UniswapScriptHelper.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/tools/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/python/prod/utils/tools/v3/__init__.py +0 -0
- {defipy-1.2.0 → defipy-2.0.0}/setup.cfg +0 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: DeFiPy
|
|
3
|
+
Version: 2.0.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: book
|
|
24
|
+
Requires-Dist: web3scout>=0.2.0; extra == "book"
|
|
25
|
+
Requires-Dist: web3<7.0,>=6.0; extra == "book"
|
|
26
|
+
Provides-Extra: anvil
|
|
27
|
+
Requires-Dist: web3<7.0,>=6.0; extra == "anvil"
|
|
28
|
+
Provides-Extra: mcp
|
|
29
|
+
Requires-Dist: mcp>=1.27.0; extra == "mcp"
|
|
30
|
+
Dynamic: author
|
|
31
|
+
Dynamic: author-email
|
|
32
|
+
Dynamic: description
|
|
33
|
+
Dynamic: description-content-type
|
|
34
|
+
Dynamic: home-page
|
|
35
|
+
Dynamic: license
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
Dynamic: provides-extra
|
|
38
|
+
Dynamic: requires-dist
|
|
39
|
+
Dynamic: summary
|
|
40
|
+
|
|
41
|
+
# DeFiPy: Python SDK for Agentic DeFi
|
|
42
|
+
|
|
43
|
+
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.
|
|
44
|
+
|
|
45
|
+
Underneath, DeFiPy is modular by protocol:
|
|
46
|
+
|
|
47
|
+
* [UniswapPy](https://github.com/defipy-devs/uniswappy)
|
|
48
|
+
* [BalancerPy](https://github.com/defipy-devs/balancerpy)
|
|
49
|
+
* [StableSwapPy](https://github.com/defipy-devs/stableswappy)
|
|
50
|
+
|
|
51
|
+
For onchain event access and scripting, pair it with [Web3Scout](https://github.com/defipy-devs/web3scout) — a companion tool for [decoding pool events](https://defipy.readthedocs.io/en/latest/onchain/pool_events.html) and [interfacing with Solidity contracts](https://defipy.readthedocs.io/en/latest/onchain/testnet_sim_univ2.html).
|
|
52
|
+
|
|
53
|
+
🔗 SPDX-Anchor: [anchorregistry.ai/AR-2026-YdPXB5g](https://anchorregistry.ai/AR-2026-YdPXB5g)
|
|
54
|
+
|
|
55
|
+
## 🆕 What's new in v2.0
|
|
56
|
+
|
|
57
|
+
v2.0 makes DeFiPy's primitives **agent-ready** without coupling the library to any specific LLM framework. Three new modules land alongside the existing 22 primitives:
|
|
58
|
+
|
|
59
|
+
* **`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.
|
|
60
|
+
* **`defipy.twin`** — the **State Twin** abstraction. `MockProvider` ships four canonical synthetic pools (V2, V3, Balancer, Stableswap) for notebooks and tests; `LiveProvider` (chain reads) lands in v2.1.
|
|
61
|
+
* **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.
|
|
62
|
+
|
|
63
|
+
### What is MCP?
|
|
64
|
+
|
|
65
|
+
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:
|
|
66
|
+
|
|
67
|
+
> *"Is the ETH/DAI V2 pool healthy? Any rug signals?"*
|
|
68
|
+
|
|
69
|
+
Claude reads the tool descriptions, picks `CheckPoolHealth`, calls it against a MockProvider twin, 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.
|
|
70
|
+
|
|
71
|
+
**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.
|
|
72
|
+
|
|
73
|
+
## 🧩 What DeFiPy offers
|
|
74
|
+
|
|
75
|
+
22 primitives across 7 categories. Each answers a specific LP question with exact math and returns a typed dataclass result:
|
|
76
|
+
|
|
77
|
+
* **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.
|
|
78
|
+
* **Pool health** — "Is this pool healthy? Any rug signals?" TVL, LP concentration, activity, threshold-based rug detection, fee-anomaly checks (V2/V3).
|
|
79
|
+
* **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.
|
|
80
|
+
* **Execution** — "What's my actual slippage? Maximum trade size before it exceeds X%? Did a swap get MEV'd?" (V2/V3).
|
|
81
|
+
* **Optimization** — Zap-in optimal swap fractions, V3 tick range evaluation, rebalance cost analysis.
|
|
82
|
+
* **Comparison** — Side-by-side same-capital analysis across protocols or V3 fee tiers.
|
|
83
|
+
* **Portfolio** — Multi-position aggregation with cross-protocol dispatch.
|
|
84
|
+
|
|
85
|
+
Full primitive catalog with LP-question mappings lives in the [v2 docs](https://defipy.org).
|
|
86
|
+
|
|
87
|
+
*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.*
|
|
88
|
+
|
|
89
|
+
## 📝 Docs
|
|
90
|
+
Visit [**DeFiPy docs**](https://defipy.org) for full documentation
|
|
91
|
+
|
|
92
|
+
## 🔍 Install
|
|
93
|
+
|
|
94
|
+
DeFiPy requires **Python 3.10 or later**. Install via pip:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
> pip install defipy
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### MCP install (Claude Desktop / Claude Code demo)
|
|
101
|
+
|
|
102
|
+
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:
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
> pip install defipy[mcp]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
### Book install (chapter 9 agents)
|
|
111
|
+
|
|
112
|
+
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:
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
> pip install defipy[book]
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
This pulls in `web3scout` on top of the core install, enabling the chain event monitoring, ABI loading, and token-fetching utilities that chapter 9's agents require. Other chapters work with the core install alone.
|
|
119
|
+
|
|
120
|
+
### Anvil install (local Foundry workflows)
|
|
121
|
+
|
|
122
|
+
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`:
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
> pip install defipy[anvil]
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`[book]` already includes everything in `[anvil]`, so book readers only need `[book]`.
|
|
129
|
+
|
|
130
|
+
### Source install
|
|
131
|
+
|
|
132
|
+
To install from source:
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
> git clone https://github.com/defipy-devs/defipy
|
|
136
|
+
> cd defipy
|
|
137
|
+
> pip install .
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### System libraries for gmpy2
|
|
141
|
+
|
|
142
|
+
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`:
|
|
143
|
+
|
|
144
|
+
**macOS (Homebrew):**
|
|
145
|
+
```
|
|
146
|
+
> brew install gmp mpfr libmpc
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
**Linux (Debian / Ubuntu):**
|
|
150
|
+
```
|
|
151
|
+
> sudo apt install libgmp-dev libmpfr-dev libmpc-dev
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
See the [gmpy2 installation docs](https://gmpy2.readthedocs.io/en/latest/install.html) for other platforms.
|
|
155
|
+
|
|
156
|
+
## 🔍 Learning Resources
|
|
157
|
+
|
|
158
|
+
DeFiPy is accompanied by educational resources for developers and researchers
|
|
159
|
+
interested in on-chain analytics and DeFi modeling.
|
|
160
|
+
|
|
161
|
+
### 📘 Textbook
|
|
162
|
+
**_DeFiPy: Python SDK for On-Chain Analytics_**
|
|
163
|
+
|
|
164
|
+
A comprehensive guide to DeFi analytics, AMM modeling, and simulation.
|
|
165
|
+
|
|
166
|
+
🔗 **Buy on Amazon:** https://www.amazon.com/dp/B0G3RV5QRB
|
|
167
|
+
|
|
168
|
+
### 🎓 Course
|
|
169
|
+
**On-Chain Analytics Foundations**
|
|
170
|
+
|
|
171
|
+
A practical course on transforming raw blockchain data into structured
|
|
172
|
+
analytics pipelines using Python.
|
|
173
|
+
|
|
174
|
+
Topics include:
|
|
175
|
+
|
|
176
|
+
- retrieving blockchain data via Ethereum RPC
|
|
177
|
+
- decoding event logs
|
|
178
|
+
- analyzing AMM swap events
|
|
179
|
+
- building DeFi analytics pipelines
|
|
180
|
+
|
|
181
|
+
🔗 **Course Page:** https://defipy.thinkific.com/products/courses/foundations
|
|
182
|
+
|
|
183
|
+
## 🚀 Quick Example (high-level: primitives + State Twin)
|
|
184
|
+
--------------------------
|
|
185
|
+
|
|
186
|
+
The fastest way to see DeFiPy at work. `MockProvider` ships canonical synthetic pools; `StateTwinBuilder` turns a snapshot into a usable exchange object; any primitive runs against it.
|
|
187
|
+
|
|
188
|
+
from defipy import AnalyzePosition
|
|
189
|
+
from defipy.twin import MockProvider, StateTwinBuilder
|
|
190
|
+
|
|
191
|
+
# Build a synthetic ETH/DAI Uniswap V2 pool
|
|
192
|
+
provider = MockProvider()
|
|
193
|
+
builder = StateTwinBuilder()
|
|
194
|
+
lp = builder.build(provider.snapshot("eth_dai_v2"))
|
|
195
|
+
|
|
196
|
+
# Ask the primitive: why is this LP position gaining or losing money?
|
|
197
|
+
result = AnalyzePosition().apply(
|
|
198
|
+
lp,
|
|
199
|
+
lp_init_amt=1.0,
|
|
200
|
+
entry_x_amt=1000,
|
|
201
|
+
entry_y_amt=100000,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
print(f"Diagnosis: {result.diagnosis}")
|
|
205
|
+
print(f"Net PnL: {result.net_pnl:.4f}")
|
|
206
|
+
print(f"IL %: {result.il_percentage:.4f}")
|
|
207
|
+
print(f"Current val: {result.current_value:.4f}")
|
|
208
|
+
|
|
209
|
+
At-entry state with 100% pool ownership yields `diagnosis=il_dominant` with zero IL and fees. Other recipes (`eth_dai_v3`, `eth_dai_balancer_50_50`, `usdc_dai_stableswap_A10`) exercise the other three AMM families; every curated primitive works against them.
|
|
210
|
+
|
|
211
|
+
For LLM-driven interaction with these primitives, see the [MCP server README](./python/mcp/README.md).
|
|
212
|
+
|
|
213
|
+
## 🧱 Quick Example (low-level: Uniswap V3 pool construction)
|
|
214
|
+
--------------------------
|
|
215
|
+
|
|
216
|
+
To construct a Uniswap V3 pool directly (outside MockProvider's canonical recipes), 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:
|
|
217
|
+
|
|
218
|
+
from defipy import *
|
|
219
|
+
|
|
220
|
+
# Step 1: Define tokens and parameters
|
|
221
|
+
eth = ERC20("ETH", "0x93")
|
|
222
|
+
tkn = ERC20("TKN", "0x111")
|
|
223
|
+
tick_spacing = 60
|
|
224
|
+
fee = 3000 # 0.3% fee tier
|
|
225
|
+
|
|
226
|
+
# Step 2: Set up exchange data for V3
|
|
227
|
+
exch_data = UniswapExchangeData(tkn0=eth, tkn1=tkn, symbol="LP", address="0x811", version='V3', tick_spacing=tick_spacing, fee=fee)
|
|
228
|
+
|
|
229
|
+
# Step 3: Initialize factory
|
|
230
|
+
factory = UniswapFactory("ETH pool factory", "0x2")
|
|
231
|
+
|
|
232
|
+
# Step 4: Deploy pool
|
|
233
|
+
lp = factory.deploy(exch_data)
|
|
234
|
+
|
|
235
|
+
# Step 5: Add initial liquidity within tick range
|
|
236
|
+
lwr_tick = UniV3Utils.getMinTick(tick_spacing)
|
|
237
|
+
upr_tick = UniV3Utils.getMaxTick(tick_spacing)
|
|
238
|
+
join = Join()
|
|
239
|
+
join.apply(lp, "user", 1000, 10000, lwr_tick, upr_tick)
|
|
240
|
+
|
|
241
|
+
# Step 6: Perform swap
|
|
242
|
+
swap = Swap()
|
|
243
|
+
out = swap.apply(lp, tkn, "user", 10)
|
|
244
|
+
|
|
245
|
+
# Check reserves and liquidity
|
|
246
|
+
lp.summary()
|
|
247
|
+
|
|
248
|
+
# OUTPUT:
|
|
249
|
+
Exchange ETH-TKN (LP)
|
|
250
|
+
Real Reserves: ETH = 999.0039930189599, TKN = 10010.0
|
|
251
|
+
Gross Liquidity: 3162.277660168379
|
|
252
|
+
|
|
253
|
+
## 🧪 Tests
|
|
254
|
+
|
|
255
|
+
DeFiPy ships 629 tests across primitives, tools, twin, packaging, and the MCP server dispatch layer. Run the full suite:
|
|
256
|
+
|
|
257
|
+
pytest python/test/ -v
|
|
258
|
+
|
|
259
|
+
Run just the primitive suite (504 tests, no MCP or twin dependencies):
|
|
260
|
+
|
|
261
|
+
pytest python/test/primitives/ -v
|
|
262
|
+
|
|
263
|
+
## License
|
|
264
|
+
Licensed under the Apache License, Version 2.0.
|
|
265
|
+
See [LICENSE](./LICENSE) and [NOTICE](./NOTICE) for details.
|
|
266
|
+
Portions of this project may include code from third-party projects under compatible open-source licenses.
|
|
@@ -0,0 +1,114 @@
|
|
|
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/builder.py
|
|
79
|
+
python/prod/twin/live_provider.py
|
|
80
|
+
python/prod/twin/mock_provider.py
|
|
81
|
+
python/prod/twin/provider.py
|
|
82
|
+
python/prod/twin/snapshot.py
|
|
83
|
+
python/prod/utils/client/__init__.py
|
|
84
|
+
python/prod/utils/client/contract/ExecuteScript.py
|
|
85
|
+
python/prod/utils/client/contract/__init__.py
|
|
86
|
+
python/prod/utils/data/BalancerPositionAnalysis.py
|
|
87
|
+
python/prod/utils/data/BalancerPriceMoveScenario.py
|
|
88
|
+
python/prod/utils/data/BreakEvenAlphas.py
|
|
89
|
+
python/prod/utils/data/BreakEvenTime.py
|
|
90
|
+
python/prod/utils/data/DepegRiskAssessment.py
|
|
91
|
+
python/prod/utils/data/DepositSplitResult.py
|
|
92
|
+
python/prod/utils/data/FeeAnomalyResult.py
|
|
93
|
+
python/prod/utils/data/FeeTierCandidate.py
|
|
94
|
+
python/prod/utils/data/FeeTierComparison.py
|
|
95
|
+
python/prod/utils/data/MEVDetectionResult.py
|
|
96
|
+
python/prod/utils/data/PoolHealth.py
|
|
97
|
+
python/prod/utils/data/PortfolioAnalysis.py
|
|
98
|
+
python/prod/utils/data/PortfolioPosition.py
|
|
99
|
+
python/prod/utils/data/PositionAnalysis.py
|
|
100
|
+
python/prod/utils/data/PriceMoveScenario.py
|
|
101
|
+
python/prod/utils/data/ProtocolComparison.py
|
|
102
|
+
python/prod/utils/data/RebalanceCostReport.py
|
|
103
|
+
python/prod/utils/data/RugSignalReport.py
|
|
104
|
+
python/prod/utils/data/SlippageAnalysis.py
|
|
105
|
+
python/prod/utils/data/StableswapPositionAnalysis.py
|
|
106
|
+
python/prod/utils/data/StableswapPriceMoveScenario.py
|
|
107
|
+
python/prod/utils/data/TickRangeCandidate.py
|
|
108
|
+
python/prod/utils/data/TickRangeEvaluation.py
|
|
109
|
+
python/prod/utils/data/TickRangeStatus.py
|
|
110
|
+
python/prod/utils/data/__init__.py
|
|
111
|
+
python/prod/utils/interfaces/__init__.py
|
|
112
|
+
python/prod/utils/tools/UniswapScriptHelper.py
|
|
113
|
+
python/prod/utils/tools/__init__.py
|
|
114
|
+
python/prod/utils/tools/v3/__init__.py
|
|
@@ -4,13 +4,18 @@ gmpy2>=2.1
|
|
|
4
4
|
pandas>=1.3
|
|
5
5
|
pydantic>=2.11.0
|
|
6
6
|
attrs>=21.0
|
|
7
|
-
requests>=2.28
|
|
8
|
-
web3>=6.0
|
|
9
7
|
termcolor>=2.4.0
|
|
10
8
|
bokeh>=3.3
|
|
11
|
-
uniswappy>=1.7.
|
|
12
|
-
balancerpy>=1.0
|
|
13
|
-
stableswappy>=1.0
|
|
9
|
+
uniswappy>=1.7.9
|
|
10
|
+
balancerpy>=1.1.0
|
|
11
|
+
stableswappy>=1.1.0
|
|
12
|
+
|
|
13
|
+
[anvil]
|
|
14
|
+
web3<7.0,>=6.0
|
|
14
15
|
|
|
15
16
|
[book]
|
|
16
17
|
web3scout>=0.2.0
|
|
18
|
+
web3<7.0,>=6.0
|
|
19
|
+
|
|
20
|
+
[mcp]
|
|
21
|
+
mcp>=1.27.0
|
defipy-2.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: DeFiPy
|
|
3
|
+
Version: 2.0.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: book
|
|
24
|
+
Requires-Dist: web3scout>=0.2.0; extra == "book"
|
|
25
|
+
Requires-Dist: web3<7.0,>=6.0; extra == "book"
|
|
26
|
+
Provides-Extra: anvil
|
|
27
|
+
Requires-Dist: web3<7.0,>=6.0; extra == "anvil"
|
|
28
|
+
Provides-Extra: mcp
|
|
29
|
+
Requires-Dist: mcp>=1.27.0; extra == "mcp"
|
|
30
|
+
Dynamic: author
|
|
31
|
+
Dynamic: author-email
|
|
32
|
+
Dynamic: description
|
|
33
|
+
Dynamic: description-content-type
|
|
34
|
+
Dynamic: home-page
|
|
35
|
+
Dynamic: license
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
Dynamic: provides-extra
|
|
38
|
+
Dynamic: requires-dist
|
|
39
|
+
Dynamic: summary
|
|
40
|
+
|
|
41
|
+
# DeFiPy: Python SDK for Agentic DeFi
|
|
42
|
+
|
|
43
|
+
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.
|
|
44
|
+
|
|
45
|
+
Underneath, DeFiPy is modular by protocol:
|
|
46
|
+
|
|
47
|
+
* [UniswapPy](https://github.com/defipy-devs/uniswappy)
|
|
48
|
+
* [BalancerPy](https://github.com/defipy-devs/balancerpy)
|
|
49
|
+
* [StableSwapPy](https://github.com/defipy-devs/stableswappy)
|
|
50
|
+
|
|
51
|
+
For onchain event access and scripting, pair it with [Web3Scout](https://github.com/defipy-devs/web3scout) — a companion tool for [decoding pool events](https://defipy.readthedocs.io/en/latest/onchain/pool_events.html) and [interfacing with Solidity contracts](https://defipy.readthedocs.io/en/latest/onchain/testnet_sim_univ2.html).
|
|
52
|
+
|
|
53
|
+
🔗 SPDX-Anchor: [anchorregistry.ai/AR-2026-YdPXB5g](https://anchorregistry.ai/AR-2026-YdPXB5g)
|
|
54
|
+
|
|
55
|
+
## 🆕 What's new in v2.0
|
|
56
|
+
|
|
57
|
+
v2.0 makes DeFiPy's primitives **agent-ready** without coupling the library to any specific LLM framework. Three new modules land alongside the existing 22 primitives:
|
|
58
|
+
|
|
59
|
+
* **`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.
|
|
60
|
+
* **`defipy.twin`** — the **State Twin** abstraction. `MockProvider` ships four canonical synthetic pools (V2, V3, Balancer, Stableswap) for notebooks and tests; `LiveProvider` (chain reads) lands in v2.1.
|
|
61
|
+
* **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.
|
|
62
|
+
|
|
63
|
+
### What is MCP?
|
|
64
|
+
|
|
65
|
+
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:
|
|
66
|
+
|
|
67
|
+
> *"Is the ETH/DAI V2 pool healthy? Any rug signals?"*
|
|
68
|
+
|
|
69
|
+
Claude reads the tool descriptions, picks `CheckPoolHealth`, calls it against a MockProvider twin, 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.
|
|
70
|
+
|
|
71
|
+
**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.
|
|
72
|
+
|
|
73
|
+
## 🧩 What DeFiPy offers
|
|
74
|
+
|
|
75
|
+
22 primitives across 7 categories. Each answers a specific LP question with exact math and returns a typed dataclass result:
|
|
76
|
+
|
|
77
|
+
* **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.
|
|
78
|
+
* **Pool health** — "Is this pool healthy? Any rug signals?" TVL, LP concentration, activity, threshold-based rug detection, fee-anomaly checks (V2/V3).
|
|
79
|
+
* **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.
|
|
80
|
+
* **Execution** — "What's my actual slippage? Maximum trade size before it exceeds X%? Did a swap get MEV'd?" (V2/V3).
|
|
81
|
+
* **Optimization** — Zap-in optimal swap fractions, V3 tick range evaluation, rebalance cost analysis.
|
|
82
|
+
* **Comparison** — Side-by-side same-capital analysis across protocols or V3 fee tiers.
|
|
83
|
+
* **Portfolio** — Multi-position aggregation with cross-protocol dispatch.
|
|
84
|
+
|
|
85
|
+
Full primitive catalog with LP-question mappings lives in the [v2 docs](https://defipy.org).
|
|
86
|
+
|
|
87
|
+
*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.*
|
|
88
|
+
|
|
89
|
+
## 📝 Docs
|
|
90
|
+
Visit [**DeFiPy docs**](https://defipy.org) for full documentation
|
|
91
|
+
|
|
92
|
+
## 🔍 Install
|
|
93
|
+
|
|
94
|
+
DeFiPy requires **Python 3.10 or later**. Install via pip:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
> pip install defipy
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### MCP install (Claude Desktop / Claude Code demo)
|
|
101
|
+
|
|
102
|
+
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:
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
> pip install defipy[mcp]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
### Book install (chapter 9 agents)
|
|
111
|
+
|
|
112
|
+
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:
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
> pip install defipy[book]
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
This pulls in `web3scout` on top of the core install, enabling the chain event monitoring, ABI loading, and token-fetching utilities that chapter 9's agents require. Other chapters work with the core install alone.
|
|
119
|
+
|
|
120
|
+
### Anvil install (local Foundry workflows)
|
|
121
|
+
|
|
122
|
+
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`:
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
> pip install defipy[anvil]
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`[book]` already includes everything in `[anvil]`, so book readers only need `[book]`.
|
|
129
|
+
|
|
130
|
+
### Source install
|
|
131
|
+
|
|
132
|
+
To install from source:
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
> git clone https://github.com/defipy-devs/defipy
|
|
136
|
+
> cd defipy
|
|
137
|
+
> pip install .
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### System libraries for gmpy2
|
|
141
|
+
|
|
142
|
+
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`:
|
|
143
|
+
|
|
144
|
+
**macOS (Homebrew):**
|
|
145
|
+
```
|
|
146
|
+
> brew install gmp mpfr libmpc
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
**Linux (Debian / Ubuntu):**
|
|
150
|
+
```
|
|
151
|
+
> sudo apt install libgmp-dev libmpfr-dev libmpc-dev
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
See the [gmpy2 installation docs](https://gmpy2.readthedocs.io/en/latest/install.html) for other platforms.
|
|
155
|
+
|
|
156
|
+
## 🔍 Learning Resources
|
|
157
|
+
|
|
158
|
+
DeFiPy is accompanied by educational resources for developers and researchers
|
|
159
|
+
interested in on-chain analytics and DeFi modeling.
|
|
160
|
+
|
|
161
|
+
### 📘 Textbook
|
|
162
|
+
**_DeFiPy: Python SDK for On-Chain Analytics_**
|
|
163
|
+
|
|
164
|
+
A comprehensive guide to DeFi analytics, AMM modeling, and simulation.
|
|
165
|
+
|
|
166
|
+
🔗 **Buy on Amazon:** https://www.amazon.com/dp/B0G3RV5QRB
|
|
167
|
+
|
|
168
|
+
### 🎓 Course
|
|
169
|
+
**On-Chain Analytics Foundations**
|
|
170
|
+
|
|
171
|
+
A practical course on transforming raw blockchain data into structured
|
|
172
|
+
analytics pipelines using Python.
|
|
173
|
+
|
|
174
|
+
Topics include:
|
|
175
|
+
|
|
176
|
+
- retrieving blockchain data via Ethereum RPC
|
|
177
|
+
- decoding event logs
|
|
178
|
+
- analyzing AMM swap events
|
|
179
|
+
- building DeFi analytics pipelines
|
|
180
|
+
|
|
181
|
+
🔗 **Course Page:** https://defipy.thinkific.com/products/courses/foundations
|
|
182
|
+
|
|
183
|
+
## 🚀 Quick Example (high-level: primitives + State Twin)
|
|
184
|
+
--------------------------
|
|
185
|
+
|
|
186
|
+
The fastest way to see DeFiPy at work. `MockProvider` ships canonical synthetic pools; `StateTwinBuilder` turns a snapshot into a usable exchange object; any primitive runs against it.
|
|
187
|
+
|
|
188
|
+
from defipy import AnalyzePosition
|
|
189
|
+
from defipy.twin import MockProvider, StateTwinBuilder
|
|
190
|
+
|
|
191
|
+
# Build a synthetic ETH/DAI Uniswap V2 pool
|
|
192
|
+
provider = MockProvider()
|
|
193
|
+
builder = StateTwinBuilder()
|
|
194
|
+
lp = builder.build(provider.snapshot("eth_dai_v2"))
|
|
195
|
+
|
|
196
|
+
# Ask the primitive: why is this LP position gaining or losing money?
|
|
197
|
+
result = AnalyzePosition().apply(
|
|
198
|
+
lp,
|
|
199
|
+
lp_init_amt=1.0,
|
|
200
|
+
entry_x_amt=1000,
|
|
201
|
+
entry_y_amt=100000,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
print(f"Diagnosis: {result.diagnosis}")
|
|
205
|
+
print(f"Net PnL: {result.net_pnl:.4f}")
|
|
206
|
+
print(f"IL %: {result.il_percentage:.4f}")
|
|
207
|
+
print(f"Current val: {result.current_value:.4f}")
|
|
208
|
+
|
|
209
|
+
At-entry state with 100% pool ownership yields `diagnosis=il_dominant` with zero IL and fees. Other recipes (`eth_dai_v3`, `eth_dai_balancer_50_50`, `usdc_dai_stableswap_A10`) exercise the other three AMM families; every curated primitive works against them.
|
|
210
|
+
|
|
211
|
+
For LLM-driven interaction with these primitives, see the [MCP server README](./python/mcp/README.md).
|
|
212
|
+
|
|
213
|
+
## 🧱 Quick Example (low-level: Uniswap V3 pool construction)
|
|
214
|
+
--------------------------
|
|
215
|
+
|
|
216
|
+
To construct a Uniswap V3 pool directly (outside MockProvider's canonical recipes), 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:
|
|
217
|
+
|
|
218
|
+
from defipy import *
|
|
219
|
+
|
|
220
|
+
# Step 1: Define tokens and parameters
|
|
221
|
+
eth = ERC20("ETH", "0x93")
|
|
222
|
+
tkn = ERC20("TKN", "0x111")
|
|
223
|
+
tick_spacing = 60
|
|
224
|
+
fee = 3000 # 0.3% fee tier
|
|
225
|
+
|
|
226
|
+
# Step 2: Set up exchange data for V3
|
|
227
|
+
exch_data = UniswapExchangeData(tkn0=eth, tkn1=tkn, symbol="LP", address="0x811", version='V3', tick_spacing=tick_spacing, fee=fee)
|
|
228
|
+
|
|
229
|
+
# Step 3: Initialize factory
|
|
230
|
+
factory = UniswapFactory("ETH pool factory", "0x2")
|
|
231
|
+
|
|
232
|
+
# Step 4: Deploy pool
|
|
233
|
+
lp = factory.deploy(exch_data)
|
|
234
|
+
|
|
235
|
+
# Step 5: Add initial liquidity within tick range
|
|
236
|
+
lwr_tick = UniV3Utils.getMinTick(tick_spacing)
|
|
237
|
+
upr_tick = UniV3Utils.getMaxTick(tick_spacing)
|
|
238
|
+
join = Join()
|
|
239
|
+
join.apply(lp, "user", 1000, 10000, lwr_tick, upr_tick)
|
|
240
|
+
|
|
241
|
+
# Step 6: Perform swap
|
|
242
|
+
swap = Swap()
|
|
243
|
+
out = swap.apply(lp, tkn, "user", 10)
|
|
244
|
+
|
|
245
|
+
# Check reserves and liquidity
|
|
246
|
+
lp.summary()
|
|
247
|
+
|
|
248
|
+
# OUTPUT:
|
|
249
|
+
Exchange ETH-TKN (LP)
|
|
250
|
+
Real Reserves: ETH = 999.0039930189599, TKN = 10010.0
|
|
251
|
+
Gross Liquidity: 3162.277660168379
|
|
252
|
+
|
|
253
|
+
## 🧪 Tests
|
|
254
|
+
|
|
255
|
+
DeFiPy ships 629 tests across primitives, tools, twin, packaging, and the MCP server dispatch layer. Run the full suite:
|
|
256
|
+
|
|
257
|
+
pytest python/test/ -v
|
|
258
|
+
|
|
259
|
+
Run just the primitive suite (504 tests, no MCP or twin dependencies):
|
|
260
|
+
|
|
261
|
+
pytest python/test/primitives/ -v
|
|
262
|
+
|
|
263
|
+
## License
|
|
264
|
+
Licensed under the Apache License, Version 2.0.
|
|
265
|
+
See [LICENSE](./LICENSE) and [NOTICE](./NOTICE) for details.
|
|
266
|
+
Portions of this project may include code from third-party projects under compatible open-source licenses.
|