@intentsolutionsio/flash-loan-simulator 1.0.0

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.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@intentsolutionsio/flash-loan-simulator",
3
+ "version": "1.0.0",
4
+ "description": "Simulate and analyze flash loan strategies including arbitrage, liquidations, and collateral swaps",
5
+ "keywords": [
6
+ "crypto",
7
+ "flash-loans",
8
+ "defi",
9
+ "aave",
10
+ "arbitrage",
11
+ "liquidation",
12
+ "ethereum",
13
+ "simulation",
14
+ "claude-code",
15
+ "claude-plugin",
16
+ "tonsofskills"
17
+ ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/jeremylongshore/claude-code-plugins-plus-skills.git",
21
+ "directory": "plugins/crypto/flash-loan-simulator"
22
+ },
23
+ "homepage": "https://tonsofskills.com/plugins/flash-loan-simulator",
24
+ "bugs": "https://github.com/jeremylongshore/claude-code-plugins-plus-skills/issues",
25
+ "license": "MIT",
26
+ "author": {
27
+ "name": "Intent Solutions IO",
28
+ "email": "jeremy@intentsolutions.ai",
29
+ "url": "https://intentsolutions.ai"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "files": [
35
+ "README.md",
36
+ ".claude-plugin",
37
+ "skills",
38
+ "agents"
39
+ ],
40
+ "scripts": {
41
+ "postinstall": "node -e \"console.log(\\\"\\\\n→ This npm package is a tracking/proof artifact. Install the plugin via:\\\\n ccpi install flash-loan-simulator\\\\n or /plugin install flash-loan-simulator@claude-code-plugins-plus in Claude Code\\\\n\\\")\""
42
+ }
43
+ }
@@ -0,0 +1,454 @@
1
+ # ARD: Flash Loan Simulator
2
+
3
+ > Part of [Tons of Skills](https://tonsofskills.com) by [Intent Solutions](https://intentsolutions.io) | [jeremylongshore.com](https://jeremylongshore.com)
4
+
5
+ ## Architectural Overview
6
+
7
+ ### Pattern: Strategy Simulation with Protocol Abstraction
8
+
9
+ The flash loan simulator uses a **strategy-protocol abstraction pattern** where different flash loan strategies are composed from protocol-agnostic building blocks, enabling simulation across multiple providers and chains.
10
+
11
+ ```
12
+ ┌─────────────────────────────────────────────────────────────────────┐
13
+ │ FLASH LOAN SIMULATOR │
14
+ ├─────────────────────────────────────────────────────────────────────┤
15
+ │ │
16
+ │ ┌─────────────┐ ┌──────────────┐ ┌─────────────────────┐ │
17
+ │ │ User │───▶│ Strategy │───▶│ Simulation │ │
18
+ │ │ Input │ │ Builder │ │ Engine │ │
19
+ │ └─────────────┘ └──────┬───────┘ └──────────┬──────────┘ │
20
+ │ │ │ │
21
+ │ ▼ ▼ │
22
+ │ ┌────────────────┐ ┌─────────────────────┐ │
23
+ │ │ Protocol │ │ Profitability │ │
24
+ │ │ Abstraction │ │ Calculator │ │
25
+ │ └───────┬────────┘ └─────────────────────┘ │
26
+ │ │ │
27
+ │ ┌─────────────────┼─────────────────┐ │
28
+ │ ▼ ▼ ▼ │
29
+ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
30
+ │ │ Aave V3 │ │ dYdX │ │ Balancer │ │
31
+ │ │ Adapter │ │ Adapter │ │ Adapter │ │
32
+ │ └────────────┘ └────────────┘ └────────────┘ │
33
+ │ │ │ │ │
34
+ │ └─────────────────┼─────────────────┘ │
35
+ │ ▼ │
36
+ │ ┌────────────────┐ │
37
+ │ │ RPC Layer │ │
38
+ │ │ (Multi-Chain)│ │
39
+ │ └───────┬────────┘ │
40
+ │ │ │
41
+ │ ▼ │
42
+ │ ┌────────────────┐ ┌─────────────────────┐ │
43
+ │ │ Formatter │───▶│ Output │ │
44
+ │ │ │ │ (Table/JSON) │ │
45
+ │ └────────────────┘ └─────────────────────┘ │
46
+ │ │
47
+ └─────────────────────────────────────────────────────────────────────┘
48
+ ```
49
+
50
+ ### Workflow
51
+
52
+ 1. **Strategy Selection**: User chooses strategy type and parameters
53
+ 2. **Protocol Resolution**: Identify best flash loan provider
54
+ 3. **Price Discovery**: Fetch current DEX prices
55
+ 4. **Simulation**: Execute virtual transaction steps
56
+ 5. **Profit Calculation**: Sum revenues, subtract all costs
57
+ 6. **Risk Assessment**: Score competition and execution risk
58
+ 7. **Output**: Present results with recommendations
59
+
60
+ ## Progressive Disclosure Strategy
61
+
62
+ ### Level 1: Quick Profitability Check (Default)
63
+ ```bash
64
+ python flash_simulator.py arbitrage ETH USDC 100 --provider aave
65
+ ```
66
+ Output: Simple profit/loss with recommendation.
67
+
68
+ ### Level 2: Detailed Breakdown
69
+ ```bash
70
+ python flash_simulator.py arbitrage ETH USDC 100 --breakdown
71
+ ```
72
+ Output: Step-by-step costs and revenues.
73
+
74
+ ### Level 3: Multi-Provider Comparison
75
+ ```bash
76
+ python flash_simulator.py arbitrage ETH USDC 100 --compare-providers
77
+ ```
78
+ Output: Aave vs dYdX vs Balancer comparison.
79
+
80
+ ### Level 4: Risk Analysis
81
+ ```bash
82
+ python flash_simulator.py arbitrage ETH USDC 100 --risk-analysis
83
+ ```
84
+ Output: MEV competition, execution risk, protocol risk scores.
85
+
86
+ ### Level 5: Full Simulation
87
+ ```bash
88
+ python flash_simulator.py arbitrage ETH USDC 100 --full --output json
89
+ ```
90
+ Output: Complete analysis with all details.
91
+
92
+ ## Tool Permission Strategy
93
+
94
+ ```yaml
95
+ allowed-tools: Read, Write, Edit, Grep, Glob, Bash(crypto:flashloan-*)
96
+ ```
97
+
98
+ ### Rationale
99
+ - **Read/Write/Edit**: Configuration and output management
100
+ - **Grep/Glob**: Search for contract addresses and ABIs
101
+ - **Bash(crypto:flashloan-*)**: Scoped to flash loan simulation scripts
102
+
103
+ ### Prohibited
104
+ - No unrestricted Bash execution
105
+ - No private key or wallet access
106
+ - No actual transaction signing
107
+ - No mainnet execution capabilities
108
+
109
+ ## Directory Structure
110
+
111
+ ```
112
+ plugins/crypto/flash-loan-simulator/
113
+ ├── .claude-plugin/
114
+ │ └── plugin.json
115
+ ├── README.md
116
+ └── skills/
117
+ └── simulating-flash-loans/
118
+ ├── PRD.md
119
+ ├── ARD.md
120
+ ├── SKILL.md
121
+ ├── scripts/
122
+ │ ├── flash_simulator.py # Main CLI entry point
123
+ │ ├── strategy_engine.py # Strategy simulation logic
124
+ │ ├── protocol_adapters.py # Aave, dYdX, Balancer adapters
125
+ │ ├── profit_calculator.py # Profitability calculations
126
+ │ ├── risk_assessor.py # Risk scoring engine
127
+ │ └── formatters.py # Output formatting
128
+ ├── references/
129
+ │ ├── errors.md
130
+ │ ├── examples.md
131
+ │ └── implementation.md
132
+ └── config/
133
+ └── settings.yaml
134
+ ```
135
+
136
+ ## Protocol Adapter Architecture
137
+
138
+ ### Flash Loan Provider Abstraction
139
+
140
+ ```python
141
+ class FlashLoanProvider(ABC):
142
+ """Abstract base for flash loan providers."""
143
+
144
+ @abstractmethod
145
+ def get_fee(self, asset: str, amount: Decimal) -> Decimal:
146
+ """Get flash loan fee for asset and amount."""
147
+ pass
148
+
149
+ @abstractmethod
150
+ def get_max_loan(self, asset: str) -> Decimal:
151
+ """Get maximum available loan for asset."""
152
+ pass
153
+
154
+ @abstractmethod
155
+ def get_supported_assets(self) -> List[str]:
156
+ """Get list of supported assets."""
157
+ pass
158
+
159
+ @abstractmethod
160
+ def simulate_loan(self, params: LoanParams) -> SimulationResult:
161
+ """Simulate flash loan execution."""
162
+ pass
163
+
164
+
165
+ class AaveV3Provider(FlashLoanProvider):
166
+ """Aave V3 flash loan provider adapter."""
167
+
168
+ FEE_RATE = Decimal("0.0009") # 0.09%
169
+
170
+ POOL_ADDRESSES = {
171
+ "ethereum": "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2",
172
+ "polygon": "0x794a61358D6845594F94dc1DB02A252b5b4814aD",
173
+ "arbitrum": "0x794a61358D6845594F94dc1DB02A252b5b4814aD",
174
+ }
175
+
176
+ def get_fee(self, asset: str, amount: Decimal) -> Decimal:
177
+ return amount * self.FEE_RATE
178
+
179
+
180
+ class DydxProvider(FlashLoanProvider):
181
+ """dYdX flash loan provider adapter (0% fee)."""
182
+
183
+ FEE_RATE = Decimal("0") # Free flash loans!
184
+
185
+ SUPPORTED_ASSETS = ["ETH", "USDC", "DAI", "WBTC"]
186
+
187
+ def get_fee(self, asset: str, amount: Decimal) -> Decimal:
188
+ return Decimal("0") # dYdX has 0% flash loan fee
189
+
190
+
191
+ class BalancerProvider(FlashLoanProvider):
192
+ """Balancer flash loan provider adapter."""
193
+
194
+ FEE_RATE = Decimal("0.0001") # 0.01% (configurable per pool)
195
+ ```
196
+
197
+ ### Strategy Pattern
198
+
199
+ ```python
200
+ class FlashLoanStrategy(ABC):
201
+ """Abstract base for flash loan strategies."""
202
+
203
+ @abstractmethod
204
+ def simulate(self, params: StrategyParams) -> StrategyResult:
205
+ """Run strategy simulation."""
206
+ pass
207
+
208
+ @abstractmethod
209
+ def calculate_profit(self, result: StrategyResult) -> ProfitBreakdown:
210
+ """Calculate net profit after all costs."""
211
+ pass
212
+
213
+
214
+ class SimpleArbitrageStrategy(FlashLoanStrategy):
215
+ """Two-DEX arbitrage: buy low, sell high."""
216
+
217
+ def simulate(self, params: StrategyParams) -> StrategyResult:
218
+ # 1. Flash loan from provider
219
+ # 2. Buy on low-price DEX
220
+ # 3. Sell on high-price DEX
221
+ # 4. Repay loan + fee
222
+ # 5. Keep profit
223
+ pass
224
+
225
+
226
+ class LiquidationStrategy(FlashLoanStrategy):
227
+ """Liquidate undercollateralized positions."""
228
+
229
+ def simulate(self, params: StrategyParams) -> StrategyResult:
230
+ # 1. Flash loan debt asset
231
+ # 2. Repay borrower's debt
232
+ # 3. Receive collateral + bonus
233
+ # 4. Swap collateral to debt asset
234
+ # 5. Repay flash loan
235
+ # 6. Keep bonus
236
+ pass
237
+ ```
238
+
239
+ ## Data Flow Architecture
240
+
241
+ ```
242
+ ┌───────────────────────────────────────────────────────────────────┐
243
+ │ DATA FLOW │
244
+ ├───────────────────────────────────────────────────────────────────┤
245
+ │ │
246
+ │ INPUT │
247
+ │ ───── │
248
+ │ Strategy: arbitrage │
249
+ │ Token: ETH → USDC → ETH │
250
+ │ Amount: 100 ETH │
251
+ │ Provider: aave │
252
+ │ │
253
+ │ │ │
254
+ │ ▼ │
255
+ │ ┌─────────────────────────────────────────────────────────────┐ │
256
+ │ │ PRICE DISCOVERY │ │
257
+ │ │ │ │
258
+ │ │ Uniswap V3: ETH/USDC = 2,543.22 │ │
259
+ │ │ SushiSwap: ETH/USDC = 2,538.50 │ │
260
+ │ │ Curve: ETH/USDC = 2,540.00 │ │
261
+ │ │ ─────────────────────────────────────────── │ │
262
+ │ │ Spread: $4.72 (0.19%) │ │
263
+ │ │ │ │
264
+ │ └─────────────────────────────────────────────────────────────┘ │
265
+ │ │ │
266
+ │ ▼ │
267
+ │ ┌─────────────────────────────────────────────────────────────┐ │
268
+ │ │ SIMULATION ENGINE │ │
269
+ │ │ │ │
270
+ │ │ Step 1: Flash borrow 100 ETH from Aave │ │
271
+ │ │ Step 2: Sell 100 ETH on Uniswap → 254,322 USDC │ │
272
+ │ │ Step 3: Buy ETH on SushiSwap → 100.186 ETH │ │
273
+ │ │ Step 4: Repay 100 ETH + 0.09 ETH fee │ │
274
+ │ │ Step 5: Profit = 0.096 ETH │ │
275
+ │ │ │ │
276
+ │ └─────────────────────────────────────────────────────────────┘ │
277
+ │ │ │
278
+ │ ▼ │
279
+ │ ┌─────────────────────────────────────────────────────────────┐ │
280
+ │ │ PROFIT CALCULATION │ │
281
+ │ │ │ │
282
+ │ │ Gross Profit: 0.186 ETH ($472.50) │ │
283
+ │ │ Flash Loan Fee: -0.090 ETH ($228.89) │ │
284
+ │ │ Gas Cost: -0.012 ETH ($30.50) │ │
285
+ │ │ ────────────────────────────────────── │ │
286
+ │ │ Net Profit: 0.084 ETH ($213.11) │ │
287
+ │ │ │ │
288
+ │ └─────────────────────────────────────────────────────────────┘ │
289
+ │ │ │
290
+ │ ▼ │
291
+ │ ┌─────────────────────────────────────────────────────────────┐ │
292
+ │ │ RISK ASSESSMENT │ │
293
+ │ │ │ │
294
+ │ │ MEV Competition: HIGH (many bots target this pair) │ │
295
+ │ │ Execution Risk: MEDIUM (slippage on large trades) │ │
296
+ │ │ Protocol Risk: LOW (Aave V3 well-audited) │ │
297
+ │ │ ────────────────────────────────────── │ │
298
+ │ │ Overall Viability: MODERATE │ │
299
+ │ │ │ │
300
+ │ └─────────────────────────────────────────────────────────────┘ │
301
+ │ │ │
302
+ │ ▼ │
303
+ │ OUTPUT │
304
+ │ ────── │
305
+ │ ┌─────────────────────────────────────────────────────────────┐ │
306
+ │ │ SIMULATION RESULT │ │
307
+ │ │ ────────────────────────────────────────────────────────── │ │
308
+ │ │ Strategy: Simple Arbitrage (Uniswap → SushiSwap) │ │
309
+ │ │ Loan Amount: 100 ETH │ │
310
+ │ │ Provider: Aave V3 (0.09% fee) │ │
311
+ │ │ Net Profit: $213.11 (0.084 ETH) │ │
312
+ │ │ ROI: 0.084% │ │
313
+ │ │ Risk Level: MODERATE │ │
314
+ │ │ │ │
315
+ │ │ ⚠️ WARNING: High MEV competition on this pair. │ │
316
+ │ │ Consider using Flashbots for execution. │ │
317
+ │ └─────────────────────────────────────────────────────────────┘ │
318
+ │ │
319
+ └───────────────────────────────────────────────────────────────────┘
320
+ ```
321
+
322
+ ## Error Handling Strategy
323
+
324
+ ### Error Categories
325
+
326
+ | Category | Examples | Response |
327
+ |----------|----------|----------|
328
+ | RPC Error | Connection timeout, rate limit | Fallback to backup RPC |
329
+ | Price Error | Stale data, no liquidity | Clear warning, abort sim |
330
+ | Strategy Error | Invalid parameters | User-friendly error message |
331
+ | Protocol Error | Contract call failed | Show revert reason |
332
+ | Calculation Error | Overflow, division by zero | Safe defaults with warning |
333
+
334
+ ### Graceful Degradation
335
+
336
+ ```python
337
+ class SimulationError(Exception):
338
+ """Base simulation error with recovery hints."""
339
+
340
+ def __init__(self, message: str, recoverable: bool, hint: str):
341
+ self.message = message
342
+ self.recoverable = recoverable
343
+ self.hint = hint
344
+
345
+
346
+ class RPCManager:
347
+ """RPC connection manager with automatic fallback."""
348
+
349
+ PROVIDERS = [
350
+ "https://rpc.ankr.com/eth",
351
+ "https://eth.llamarpc.com",
352
+ "https://ethereum.publicnode.com",
353
+ ]
354
+
355
+ async def call_with_fallback(self, method: str, params: list):
356
+ for rpc in self.PROVIDERS:
357
+ try:
358
+ return await self._call(rpc, method, params)
359
+ except RPCError:
360
+ continue
361
+ raise AllRPCsFailedError("All RPC providers failed")
362
+ ```
363
+
364
+ ## Composability & Stacking
365
+
366
+ ### Compatible Skills
367
+
368
+ | Skill | Integration | Data Flow |
369
+ |-------|-------------|-----------|
370
+ | dex-aggregator-router | Route optimization | Shares DEX price data |
371
+ | gas-fee-optimizer | Gas estimation | Provides gas price input |
372
+ | liquidity-pool-analyzer | Pool metrics | Shares liquidity data |
373
+ | arbitrage-opportunity-finder | Opportunity feed | Sends arbitrage signals |
374
+
375
+ ### Stacking Example
376
+
377
+ ```bash
378
+ # Find arbitrage → Simulate flash loan → Assess risk
379
+ python arbitrage_finder.py --output opportunities.json
380
+ python flash_simulator.py --opportunities opportunities.json --simulate-all
381
+ ```
382
+
383
+ ## Performance & Scalability
384
+
385
+ ### Caching Strategy
386
+
387
+ | Data Type | TTL | Storage |
388
+ |-----------|-----|---------|
389
+ | Protocol ABIs | 24h | File cache |
390
+ | Token metadata | 24h | File cache |
391
+ | DEX prices | 30s | Memory |
392
+ | Gas prices | 15s | Memory |
393
+ | Simulation results | 0 | No cache (real-time) |
394
+
395
+ ### Performance Targets
396
+
397
+ | Metric | Target | Measurement |
398
+ |--------|--------|-------------|
399
+ | Simple simulation | <3s | Single strategy |
400
+ | Full analysis | <10s | All providers + risk |
401
+ | Batch simulation | <30s | 10 strategies |
402
+ | Memory usage | <200MB | Peak during simulation |
403
+
404
+ ## Testing Strategy
405
+
406
+ ### Unit Tests
407
+ - Protocol adapter fee calculations
408
+ - Profit calculation math
409
+ - Risk scoring algorithms
410
+ - Gas estimation accuracy
411
+
412
+ ### Integration Tests
413
+ - RPC connectivity (mocked)
414
+ - Multi-provider comparison
415
+ - Strategy composition
416
+
417
+ ### Acceptance Tests
418
+ - Simulation matches historical actual profits (±10%)
419
+ - All strategy types complete without error
420
+ - Free RPC tier sufficient for basic usage
421
+
422
+ ## Security & Compliance
423
+
424
+ ### Safety Measures
425
+ - **No execution**: Simulation only, never signs transactions
426
+ - **No private keys**: Tool cannot access wallets
427
+ - **Read-only RPC**: Only view functions, no state changes
428
+ - **Educational disclaimer**: Clear warnings about real risks
429
+
430
+ ### Data Handling
431
+ - No sensitive data storage
432
+ - API keys in environment variables only
433
+ - No transaction broadcasting
434
+
435
+ ## Dependencies
436
+
437
+ ### Python Packages
438
+ ```
439
+ web3>=6.0.0 # Ethereum interaction
440
+ httpx>=0.24.0 # Async HTTP client
441
+ pydantic>=2.0 # Data validation
442
+ rich>=13.0 # Terminal formatting
443
+ ```
444
+
445
+ ### External Services
446
+ - Free RPC endpoints (Ankr, Chainstack free tier, Infura free tier)
447
+ - DeFiLlama API (protocol TVL)
448
+ - Etherscan API (gas oracle)
449
+
450
+ ### Protocol Contracts (Read-Only)
451
+ - Aave V3 Pool
452
+ - dYdX Solo Margin
453
+ - Balancer Vault
454
+ - Uniswap V3 Router