@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.
@@ -0,0 +1,532 @@
1
+ # Flash Loan Simulator - Examples
2
+
3
+ ## Quick Start Examples
4
+
5
+ ### Example 1: Simple ETH/USDC Arbitrage
6
+
7
+ Simulate buying ETH on SushiSwap and selling on Uniswap:
8
+
9
+ ```bash
10
+ python flash_simulator.py arbitrage ETH USDC 100 \
11
+ --dex-buy sushiswap \
12
+ --dex-sell uniswap \
13
+ --provider aave
14
+ ```
15
+
16
+ **Expected Output:**
17
+ ```
18
+ ==================== FLASH LOAN SIMULATION ====================
19
+
20
+ ┌─────────────────────────── SUMMARY ────────────────────────────┐
21
+ │ Strategy: SIMPLE_ARBITRAGE │
22
+ │ Loan: 100 ETH │
23
+ │ Provider: aave │
24
+ │ Profitable: YES ✓ │
25
+ └────────────────────────────────────────────────────────────────┘
26
+
27
+ ----------------------------------------------------------------------
28
+ TRANSACTION STEPS
29
+ ----------------------------------------------------------------------
30
+
31
+ 1. [Aave] flash_loan
32
+ ETH → ETH
33
+ 100.000000 → 100.000000
34
+ Gas: ~100,000 units
35
+
36
+ 2. [SushiSwap] swap
37
+ ETH → USDC
38
+ 100.000000 → 253850.000000
39
+ Gas: ~150,000 units
40
+
41
+ 3. [Uniswap] swap
42
+ USDC → ETH
43
+ 253850.000000 → 100.188120
44
+ Gas: ~150,000 units
45
+
46
+ 4. [Aave] repay
47
+ ETH → ETH
48
+ 100.090000 → 100.090000
49
+ Gas: ~50,000 units
50
+
51
+ ----------------------------------------------------------------------
52
+ PROFIT BREAKDOWN
53
+ ----------------------------------------------------------------------
54
+ Gross Profit: +0.188120 ETH
55
+ Flash Loan Fee: -0.090000 ETH
56
+ Gas Cost: -0.013500 ETH ($33.75)
57
+ ────────────────────────────────────────
58
+ Net Profit: +0.084620 ETH ($211.55)
59
+ ROI: 0.0846%
60
+ ```
61
+
62
+ ---
63
+
64
+ ### Example 2: Compare Flash Loan Providers
65
+
66
+ Find the cheapest provider for a 100 ETH loan:
67
+
68
+ ```bash
69
+ python flash_simulator.py compare ETH 100
70
+ ```
71
+
72
+ **Expected Output:**
73
+ ```
74
+ =================== PROVIDER COMPARISON ===================
75
+
76
+ Comparing 100 ETH flash loan:
77
+
78
+ Provider Fee % Fee Amount Gas OH Chains
79
+ ------------------------------------------------------------------
80
+ dYdX 0.00% 0.0000 ETH 150,000 ethereum
81
+ Balancer 0.01% 0.0100 ETH 80,000 ethereum, polygon...
82
+ Aave V3 0.09% 0.0900 ETH 100,000 ethereum, polygon...
83
+ Uniswap V3 0.30% 0.3000 ETH 120,000 ethereum, polygon...
84
+
85
+ Recommended: dYdX
86
+ (FREE flash loan!)
87
+ ```
88
+
89
+ ---
90
+
91
+ ### Example 3: Full Analysis with Risk Assessment
92
+
93
+ Run a complete analysis with provider comparison and risk scoring:
94
+
95
+ ```bash
96
+ python flash_simulator.py arbitrage ETH USDC 100 --full
97
+ ```
98
+
99
+ **Expected Output:**
100
+ ```
101
+ ==================== FLASH LOAN SIMULATION ====================
102
+ [... strategy result ...]
103
+
104
+ ==================== PROFIT BREAKDOWN ====================
105
+
106
+ Gross Revenue: 0.188120 ETH
107
+
108
+ Costs:
109
+ Flash Loan Fee: -0.090000 ETH
110
+ Gas Cost: -0.013500 ETH ($33.75)
111
+ Est. Slippage: -0.500000 ETH
112
+ DEX Fees: ~0.600000 ETH (in price)
113
+ ─────────────────────────────────────────────
114
+ Total Costs: -0.603500 ETH
115
+
116
+ Net Profit: -0.415380 ETH (-$1038.45)
117
+ ROI: -0.4154%
118
+ Breakeven Gas: 0.0 gwei
119
+
120
+ ✗ NOT PROFITABLE
121
+
122
+ ==================== RISK ASSESSMENT ====================
123
+
124
+ Overall Risk: 🟠 HIGH
125
+ Risk Score: 65/100
126
+ Viability: CAUTION
127
+
128
+ ----------------------------------------------------------------------
129
+ RISK FACTORS
130
+ ----------------------------------------------------------------------
131
+
132
+ 🔴 MEV Competition: CRITICAL (90)
133
+ High bot activity on ETH pairs
134
+ → Use Flashbots Protect or private transactions
135
+
136
+ 🟡 Execution Risk: MEDIUM (45)
137
+ 4 steps with gas-sensitive timing
138
+ → Set tight slippage tolerance; use gas price oracles
139
+
140
+ 🟢 Protocol Risk: LOW (18)
141
+ Using 2 protocol(s): aave, sushiswap
142
+ → Verify protocol audits; monitor for exploits
143
+
144
+ 🟡 Liquidity Risk: MEDIUM (35)
145
+ $250,000 trade may cause significant slippage
146
+ → Check pool liquidity; consider splitting order
147
+
148
+ 🔴 Profit Margin: CRITICAL (100)
149
+ -0.415% profit margin (NEGATIVE!)
150
+ → Increase trade size or wait for better opportunity
151
+
152
+ ----------------------------------------------------------------------
153
+ WARNINGS
154
+ ----------------------------------------------------------------------
155
+ ⚠️ MEV Competition: High bot activity on ETH pairs
156
+ ⚠️ Profit Margin: -0.415% profit margin (NEGATIVE!)
157
+
158
+ ----------------------------------------------------------------------
159
+ RECOMMENDATIONS
160
+ ----------------------------------------------------------------------
161
+ • Use Flashbots Protect to avoid sandwich attacks
162
+ • Consider private transaction submission
163
+ • Strategy is UNPROFITABLE - do not execute
164
+ ```
165
+
166
+ ---
167
+
168
+ ### Example 4: Triangular Arbitrage
169
+
170
+ Simulate a three-hop circular arbitrage:
171
+
172
+ ```bash
173
+ python flash_simulator.py triangular ETH USDC WBTC ETH --amount 50
174
+ ```
175
+
176
+ **Expected Output:**
177
+ ```
178
+ ==================== FLASH LOAN SIMULATION ====================
179
+
180
+ ┌─────────────────────────── SUMMARY ────────────────────────────┐
181
+ │ Strategy: TRIANGULAR_ARBITRAGE │
182
+ │ Loan: 50 ETH │
183
+ │ Provider: aave │
184
+ │ Profitable: YES ✓ │
185
+ └────────────────────────────────────────────────────────────────┘
186
+
187
+ ----------------------------------------------------------------------
188
+ TRANSACTION STEPS
189
+ ----------------------------------------------------------------------
190
+
191
+ 1. [Aave] flash_loan
192
+ ETH → ETH
193
+ 50.000000 → 50.000000
194
+ Gas: ~100,000 units
195
+
196
+ 2. [Uniswap] swap
197
+ ETH → USDC
198
+ 50.000000 → 127500.000000
199
+ Gas: ~150,000 units
200
+
201
+ 3. [Curve] swap
202
+ USDC → WBTC
203
+ 127500.000000 → 1.870000
204
+ Gas: ~200,000 units
205
+
206
+ 4. [SushiSwap] swap
207
+ WBTC → ETH
208
+ 1.870000 → 50.120000
209
+ Gas: ~150,000 units
210
+
211
+ 5. [Aave] repay
212
+ ETH → ETH
213
+ 50.045000 → 50.045000
214
+ Gas: ~50,000 units
215
+
216
+ ----------------------------------------------------------------------
217
+ PROFIT BREAKDOWN
218
+ ----------------------------------------------------------------------
219
+ Gross Profit: +0.120000 ETH
220
+ Flash Loan Fee: -0.045000 ETH
221
+ Gas Cost: -0.019500 ETH ($48.75)
222
+ ────────────────────────────────────────
223
+ Net Profit: +0.055500 ETH ($138.75)
224
+ ROI: 0.1110%
225
+ ```
226
+
227
+ ---
228
+
229
+ ### Example 5: Liquidation Simulation
230
+
231
+ Analyze a potential Aave liquidation opportunity:
232
+
233
+ ```bash
234
+ python flash_simulator.py liquidation \
235
+ --protocol aave \
236
+ --collateral ETH \
237
+ --debt USDC \
238
+ --amount 10000 \
239
+ --health-factor 0.95
240
+ ```
241
+
242
+ **Expected Output:**
243
+ ```
244
+ ==================== FLASH LOAN SIMULATION ====================
245
+
246
+ ┌─────────────────────────── SUMMARY ────────────────────────────┐
247
+ │ Strategy: LIQUIDATION │
248
+ │ Loan: 10000 USDC │
249
+ │ Provider: aave │
250
+ │ Profitable: YES ✓ │
251
+ └────────────────────────────────────────────────────────────────┘
252
+
253
+ ----------------------------------------------------------------------
254
+ TRANSACTION STEPS
255
+ ----------------------------------------------------------------------
256
+
257
+ 1. [Aave] flash_loan
258
+ USDC → USDC
259
+ 10000.000000 → 10000.000000
260
+ Gas: ~100,000 units
261
+
262
+ 2. [Aave] liquidation_call
263
+ USDC → ETH
264
+ 10000.000000 → 4.200000
265
+ Gas: ~300,000 units
266
+
267
+ 3. [Uniswap] swap
268
+ ETH → USDC
269
+ 4.200000 → 10710.000000
270
+ Gas: ~150,000 units
271
+
272
+ 4. [Aave] repay
273
+ USDC → USDC
274
+ 10009.000000 → 10009.000000
275
+ Gas: ~50,000 units
276
+
277
+ ----------------------------------------------------------------------
278
+ PROFIT BREAKDOWN
279
+ ----------------------------------------------------------------------
280
+ Gross Profit: +710.000000 USDC
281
+ Flash Loan Fee: -9.000000 USDC
282
+ Gas Cost: -18.000000 USDC
283
+ ────────────────────────────────────────
284
+ Net Profit: +683.000000 USDC ($683.00)
285
+ ROI: 6.8300%
286
+ ```
287
+
288
+ ---
289
+
290
+ ### Example 6: JSON Output for Integration
291
+
292
+ Export simulation results as JSON for programmatic use:
293
+
294
+ ```bash
295
+ python flash_simulator.py arbitrage ETH USDC 100 --full --output json > simulation.json
296
+ ```
297
+
298
+ **Example JSON Output:**
299
+ ```json
300
+ {
301
+ "simulation": {
302
+ "strategy_type": "SIMPLE_ARBITRAGE",
303
+ "loan_asset": "ETH",
304
+ "loan_amount": 100.0,
305
+ "provider": "aave",
306
+ "is_profitable": true
307
+ },
308
+ "profit": {
309
+ "gross_profit": 0.18812,
310
+ "loan_fee": 0.09,
311
+ "gas_cost_eth": 0.0135,
312
+ "gas_cost_usd": 33.75,
313
+ "net_profit": 0.08462,
314
+ "net_profit_usd": 211.55,
315
+ "roi_percent": 0.0846
316
+ },
317
+ "steps": [
318
+ {
319
+ "protocol": "Aave",
320
+ "action": "flash_loan",
321
+ "asset_in": "ETH",
322
+ "asset_out": "ETH",
323
+ "amount_in": 100.0,
324
+ "amount_out": 100.0,
325
+ "gas_estimate": 100000
326
+ }
327
+ ],
328
+ "risk": {
329
+ "overall_level": "HIGH",
330
+ "overall_score": 65.0,
331
+ "viability": "CAUTION",
332
+ "factors": [
333
+ {
334
+ "name": "MEV Competition",
335
+ "level": "CRITICAL",
336
+ "score": 90.0,
337
+ "description": "High bot activity on ETH pairs",
338
+ "mitigation": "Use Flashbots Protect or private transactions"
339
+ }
340
+ ],
341
+ "warnings": ["MEV Competition: High bot activity on ETH pairs"],
342
+ "recommendations": ["Use Flashbots Protect to avoid sandwich attacks"]
343
+ },
344
+ "providers": [
345
+ {
346
+ "name": "dYdX",
347
+ "fee_rate": 0.0,
348
+ "fee_amount": 0.0,
349
+ "max_available": 50000.0,
350
+ "gas_overhead": 150000,
351
+ "supported_chains": ["ethereum"]
352
+ }
353
+ ]
354
+ }
355
+ ```
356
+
357
+ ---
358
+
359
+ ### Example 7: Using dYdX for Zero-Fee Loans
360
+
361
+ Maximize profit by using dYdX's free flash loans:
362
+
363
+ ```bash
364
+ python flash_simulator.py arbitrage ETH USDC 100 \
365
+ --provider dydx \
366
+ --dex-buy sushiswap \
367
+ --dex-sell uniswap \
368
+ --risk-analysis
369
+ ```
370
+
371
+ **Key Difference:**
372
+ - Flash loan fee: 0.00 ETH (vs 0.09 ETH with Aave)
373
+ - Net profit increases by ~$225
374
+
375
+ ---
376
+
377
+ ### Example 8: Custom Gas and ETH Price
378
+
379
+ Simulate with current market conditions:
380
+
381
+ ```bash
382
+ python flash_simulator.py arbitrage ETH USDC 100 \
383
+ --eth-price 3500 \
384
+ --gas-price 50 \
385
+ --full
386
+ ```
387
+
388
+ This adjusts:
389
+ - All USD calculations use $3,500/ETH
390
+ - Gas costs calculated at 50 gwei
391
+ - Breakeven gas price recalculated
392
+
393
+ ---
394
+
395
+ ## Programmatic Usage
396
+
397
+ ### Python Script Example
398
+
399
+ ```python
400
+ #!/usr/bin/env python3
401
+ """Example: Run multiple simulations programmatically."""
402
+
403
+ from decimal import Decimal
404
+ from strategy_engine import StrategyFactory, StrategyType, ArbitrageParams
405
+ from profit_calculator import ProfitCalculator
406
+ from risk_assessor import RiskAssessor
407
+ from protocol_adapters import ProviderManager
408
+
409
+ def analyze_arbitrage_opportunity(
410
+ input_token: str,
411
+ output_token: str,
412
+ amount: float,
413
+ dex_buy: str,
414
+ dex_sell: str,
415
+ ) -> dict:
416
+ """Analyze an arbitrage opportunity across all providers."""
417
+
418
+ factory = StrategyFactory()
419
+ calculator = ProfitCalculator(eth_price_usd=2500.0, gas_price_gwei=30.0)
420
+ assessor = RiskAssessor(eth_price_usd=2500.0)
421
+ manager = ProviderManager()
422
+
423
+ results = []
424
+
425
+ for provider_name in manager.list_providers():
426
+ strategy = factory.create(StrategyType.SIMPLE_ARBITRAGE)
427
+
428
+ params = ArbitrageParams(
429
+ input_token=input_token,
430
+ output_token=output_token,
431
+ amount=Decimal(str(amount)),
432
+ dex_buy=dex_buy,
433
+ dex_sell=dex_sell,
434
+ provider=provider_name,
435
+ )
436
+
437
+ result = strategy.simulate(params)
438
+ breakdown = calculator.calculate_breakdown(result)
439
+ assessment = assessor.assess(result)
440
+
441
+ results.append({
442
+ "provider": provider_name,
443
+ "net_profit_eth": float(result.net_profit),
444
+ "net_profit_usd": float(result.net_profit_usd),
445
+ "roi_percent": result.roi_percent,
446
+ "risk_score": assessment.overall_score,
447
+ "viability": assessment.viability,
448
+ "is_profitable": result.is_profitable,
449
+ })
450
+
451
+ # Sort by net profit
452
+ results.sort(key=lambda x: x["net_profit_usd"], reverse=True)
453
+
454
+ return {
455
+ "opportunity": f"{input_token}/{output_token}",
456
+ "amount": amount,
457
+ "best_provider": results[0]["provider"] if results else None,
458
+ "providers": results,
459
+ }
460
+
461
+
462
+ if __name__ == "__main__":
463
+ # Analyze ETH/USDC arbitrage opportunity
464
+ analysis = analyze_arbitrage_opportunity(
465
+ input_token="ETH",
466
+ output_token="USDC",
467
+ amount=100,
468
+ dex_buy="sushiswap",
469
+ dex_sell="uniswap",
470
+ )
471
+
472
+ print(f"Best provider: {analysis['best_provider']}")
473
+ for p in analysis["providers"]:
474
+ print(
475
+ f" {p['provider']}: ${p['net_profit_usd']:.2f} "
476
+ f"(Risk: {p['risk_score']:.0f}, {p['viability']})"
477
+ )
478
+ ```
479
+
480
+ ---
481
+
482
+ ## Integration Patterns
483
+
484
+ ### Batch Analysis
485
+ ```bash
486
+ # Analyze multiple pairs
487
+ for pair in "ETH-USDC" "WBTC-ETH" "ETH-DAI"; do
488
+ IFS='-' read -r input output <<< "$pair"
489
+ python flash_simulator.py arbitrage $input $output 100 --output json
490
+ done
491
+ ```
492
+
493
+ ### Pipeline Integration
494
+ ```bash
495
+ # Feed into analysis pipeline
496
+ python flash_simulator.py arbitrage ETH USDC 100 --output json | \
497
+ jq '.risk.viability == "GO"'
498
+ ```
499
+
500
+ ### Automated Monitoring
501
+ ```bash
502
+ # Check profitability every minute
503
+ while true; do
504
+ result=$(python flash_simulator.py arbitrage ETH USDC 100 --output json)
505
+ profitable=$(echo "$result" | jq '.simulation.is_profitable')
506
+ if [ "$profitable" = "true" ]; then
507
+ echo "PROFITABLE OPPORTUNITY DETECTED"
508
+ echo "$result" | jq '.profit'
509
+ fi
510
+ sleep 60
511
+ done
512
+ ```
513
+
514
+ ---
515
+
516
+ ## Disclaimer
517
+
518
+ All examples are for educational purposes only. Flash loan strategies involve significant risks:
519
+
520
+ 1. **Smart Contract Risk**: Bugs can cause total loss
521
+ 2. **MEV Risk**: Bots may front-run your transactions
522
+ 3. **Execution Risk**: Gas prices can spike unexpectedly
523
+ 4. **Market Risk**: Prices change between simulation and execution
524
+
525
+ Always:
526
+ - Test on testnets first
527
+ - Start with small amounts
528
+ - Use MEV protection in production
529
+ - Verify protocol audits
530
+
531
+ ---
532
+ *[Tons of Skills](https://tonsofskills.com) by [Intent Solutions](https://intentsolutions.io) | [jeremylongshore.com](https://jeremylongshore.com)*
@@ -0,0 +1,73 @@
1
+ # Implementation Details
2
+
3
+ ## Flash Loan Provider Comparison
4
+
5
+ | Provider | Fee | Best For | Chains |
6
+ |----------|-----|----------|--------|
7
+ | dYdX | 0% | Maximum profit | Ethereum |
8
+ | Balancer | 0.01% | Pool tokens | ETH, Polygon, Arbitrum |
9
+ | Aave V3 | 0.09% | Any token | ETH, Polygon, Arbitrum, Optimism |
10
+ | Uniswap V3 | ~0.3% | Specific pairs | ETH, Polygon, Arbitrum |
11
+
12
+ ## Supported Strategies
13
+
14
+ 1. **Simple Arbitrage**: Buy on DEX A, sell on DEX B. Requires price discrepancy > fees + gas.
15
+ 2. **Triangular Arbitrage**: A->B->C->A circular path. More complex but finds hidden opportunities.
16
+ 3. **Liquidation**: Repay underwater debt, claim collateral bonus (typically 5-15% on Aave).
17
+ 4. **Collateral Swap**: Replace collateral without closing position. Useful for risk rotation.
18
+ 5. **Self-Liquidation**: Efficiently close own position when health factor is low.
19
+ 6. **Debt Refinancing**: Move debt to better rates across protocols.
20
+
21
+ ## Triangular Arbitrage Output Breakdown
22
+
23
+ ```
24
+ Path: ETH -> USDC -> WBTC -> ETH
25
+ Gross: +0.15 ETH
26
+ Fees: -0.045 ETH (3 swaps)
27
+ Loan: -0.045 ETH (Aave fee)
28
+ Gas: -0.02 ETH
29
+ ---------------------
30
+ Net: +0.04 ETH ($101.73)
31
+ ```
32
+
33
+ ## Risk Analysis Scoring
34
+
35
+ When `--risk-analysis` is enabled, four risk factors are scored 0-100:
36
+
37
+ - **MEV Competition** (0-100): Measures bot activity on the token pair. Score > 70 means heavy competition from established searchers.
38
+ - **Execution Risk** (0-100): Slippage sensitivity and timing requirements. Higher scores mean tighter execution windows.
39
+ - **Protocol Risk** (0-100): Smart contract maturity, audit status, oracle reliability. Lower is safer.
40
+ - **Liquidity Risk** (0-100): Whether pool depth supports the trade size. Score > 80 means trade may move price significantly.
41
+
42
+ Overall viability grades:
43
+ - **A**: All risks low, high confidence
44
+ - **B**: Moderate risks, proceed with caution
45
+ - **C**: High risks, likely unprofitable
46
+ - **F**: Do not attempt
47
+
48
+ ## Output Modes
49
+
50
+ **Quick Mode** (default):
51
+ - Net profit/loss, provider recommendation, Go/No-Go verdict
52
+
53
+ **Breakdown Mode** (`--breakdown`):
54
+ - Step-by-step transaction flow, individual cost components, slippage estimates
55
+
56
+ **Comparison Mode** (`--compare-providers`):
57
+ - All providers ranked by net profit, fee differences, liquidity availability
58
+
59
+ **Risk Analysis** (`--risk-analysis`):
60
+ - Competition score, execution probability, protocol safety, overall viability grade
61
+
62
+ ## Educational Disclaimer
63
+
64
+ **FOR EDUCATIONAL PURPOSES ONLY.** Flash loan strategies involve significant risks:
65
+ - Smart contract bugs can cause total loss of borrowed funds
66
+ - MEV bots compete for the same opportunities with faster infrastructure
67
+ - Gas costs can exceed profits, especially during network congestion
68
+ - Protocol exploits may have legal implications
69
+
70
+ Never deploy unaudited code. Start with testnets. Consult legal counsel for compliance.
71
+
72
+ ---
73
+ *[Tons of Skills](https://tonsofskills.com) by [Intent Solutions](https://intentsolutions.io) | [jeremylongshore.com](https://jeremylongshore.com)*