Files
27-combi/README.md
2026-02-09 21:51:30 -08:00

278 lines
7.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Aave Stablecoin Looping Tool
A TypeScript/Node.js tool for executing stablecoin leverage loops on Aave v3 with multi-chain support, configurable wallet providers, DEX integrations, and comprehensive safety monitoring.
## Features
- **Multi-Chain Support**: Ethereum, Arbitrum, Polygon, Optimism, Base
- **Multiple Wallet Providers**: Private key, Keystore file, EIP-1193 (MetaMask)
- **Multiple DEX Integrations**: Uniswap V3, Curve, 1inch aggregator
- **Execution Modes**: Direct transaction execution or flash loan atomic execution
- **Safety Features**:
- Health factor monitoring
- Price deviation checks (depeg protection)
- Loop limit enforcement
- Pre-execution validation
- Real-time position monitoring
## Installation
```bash
npm install
```
## Configuration
Copy the environment variables template and configure:
```bash
cp .env.example .env
```
Edit `.env` with your configuration:
### Network Configuration
- `NETWORK`: Network to use (`ethereum`, `arbitrum`, `polygon`, `optimism`, `base`)
- `RPC_URL`: RPC endpoint URL
### Wallet Configuration
Choose one wallet provider type:
**Private Key:**
- `WALLET_PROVIDER_TYPE=private_key`
- `PRIVATE_KEY=your_private_key_here`
**Keystore File:**
- `WALLET_PROVIDER_TYPE=keystore`
- `KEYSTORE_PATH=./wallet.json`
- `KEYSTORE_PASSWORD=your_password_here`
**EIP-1193 (MetaMask):**
- `WALLET_PROVIDER_TYPE=eip1193`
- `EIP1193_PROVIDER_URL=http://localhost:8545`
### Aave Configuration
- `INITIAL_COLLATERAL_AMOUNT`: Starting collateral amount (default: 100000)
- `COLLATERAL_ASSET`: Collateral token (`USDC`, `USDT`, `DAI`)
- `BORROW_ASSET`: Asset to borrow (`USDC`, `USDT`, `DAI`)
- `LTV_PERCENTAGE`: Loan-to-value percentage (default: 75)
- `NUM_LOOPS`: Number of loops to execute (default: 8)
- `MIN_HEALTH_FACTOR`: Minimum health factor threshold (default: 1.1)
- `MAX_LOOPS`: Maximum allowed loops (default: 10)
### DEX Configuration
- `DEX_PROVIDER`: DEX to use (`uniswap_v3`, `curve`, `1inch`)
- `SLIPPAGE_TOLERANCE`: Slippage tolerance (default: 0.02 = 2%)
- `ONEINCH_API_KEY`: API key for 1inch (optional, but recommended)
### Execution Mode
- `EXECUTION_MODE`: Execution mode (`direct` or `flash_loan`)
### Safety Configuration
- `PRICE_DEVIATION_THRESHOLD`: Price deviation threshold (default: 0.003 = 0.3%)
- `ENABLE_PRICE_CHECKS`: Enable price deviation checks (default: true)
### Gas Configuration
- `MAX_GAS_PRICE_GWEI`: Maximum gas price in Gwei (default: 100)
- `GAS_LIMIT_MULTIPLIER`: Gas limit multiplier (default: 1.2)
## Usage
### Build
```bash
npm run build
```
### Execute Looping Strategy
```bash
npm start execute
```
Or with dry-run (simulation only):
```bash
npm start execute --dry-run
```
### Check Position Status
```bash
npm start status
```
### Development Mode
Run directly with TypeScript:
```bash
npm run dev execute
```
## How It Works
### Loop Strategy
1. **Supply Initial Collateral**: Supply USDC/USDT/DAI to Aave as collateral
2. **Borrow**: Borrow against collateral at configured LTV percentage
3. **Swap**: Swap borrowed asset back to collateral asset via DEX
4. **Re-supply**: Supply swapped amount as additional collateral
5. **Repeat**: Execute steps 2-4 for configured number of loops
### Example
With $100,000 USDC initial collateral and 75% LTV:
- Loop 1: Supply $100k → Borrow $75k DAI → Swap to $75k USDC → Re-supply
- Loop 2: Supply $75k → Borrow $56.25k DAI → Swap to $56.25k USDC → Re-supply
- ... and so on
After 8 loops, you'll have approximately **~2.7× effective supplied collateral** with a health factor around **1.096** (depending on fees and price movements).
### Safety Features
- **Health Factor Monitoring**: Continuously monitors health factor and stops if it drops below threshold
- **Price Deviation Checks**: Protects against stablecoin depegs
- **Loop Limits**: Enforces maximum number of loops
- **Pre-execution Validation**: Validates all conditions before starting
## Execution Modes
### Direct Execution
Executes each step as a separate transaction. This is the default and recommended mode for most users.
**Pros:**
- Simple and straightforward
- Can monitor progress after each step
- Easier to debug
**Cons:**
- Multiple transactions (higher gas costs)
- Not atomic (partial execution possible)
### Flash Loan Execution
Executes all loops in a single atomic transaction using Aave flash loans. **Requires a custom smart contract deployment.**
**Pros:**
- Atomic execution (all or nothing)
- Single transaction (lower total gas)
- No partial execution risk
**Cons:**
- Requires smart contract development and deployment
- More complex setup
## DEX Providers
### Uniswap V3
Best for most stablecoin pairs. Automatically selects optimal fee tier (0.01%, 0.05%, or 0.3%).
### Curve
Optimized for stablecoin swaps with low slippage. Requires pool configuration.
### 1inch Aggregator
Aggregates liquidity from multiple DEXes for best prices. Requires API key for production use.
## Safety Considerations
⚠️ **IMPORTANT WARNINGS:**
1. **Liquidation Risk**: If health factor drops below 1.0, your position can be liquidated
2. **Stablecoin Depeg Risk**: If stablecoins depeg significantly, your position may become unhealthy
3. **Smart Contract Risk**: Interacting with DeFi protocols carries smart contract risk
4. **Gas Costs**: Multiple transactions can result in significant gas costs
5. **Slippage**: Large swaps may experience slippage, reducing efficiency
**Recommendations:**
- Start with small amounts on testnets
- Use conservative LTV percentages (65-70% instead of 75%)
- Monitor health factor regularly
- Keep a safety buffer above minimum health factor
- Test thoroughly before using on mainnet
## Network-Specific Notes
### Ethereum Mainnet
- Highest security and liquidity
- Highest gas costs
- All features fully supported
### Arbitrum
- Lower gas costs
- Good liquidity for stablecoins
- Recommended for larger positions
### Polygon
- Very low gas costs
- Good for testing and smaller positions
- Check token availability
### Optimism & Base
- Low gas costs
- Growing ecosystem
- Verify contract addresses
## Troubleshooting
### Insufficient Balance
Ensure you have enough collateral token balance in your wallet.
### Health Factor Too Low
- Reduce LTV percentage
- Reduce number of loops
- Increase minimum health factor threshold
### Transaction Failures
- Check gas prices (may be too high)
- Verify network connectivity
- Check token approvals
- Ensure sufficient gas limit
### DEX Quote Failures
- Verify token pair has liquidity
- Check DEX configuration
- Try different DEX provider
## Development
### Project Structure
```
src/
├── aave/ # Aave v3 integration
├── config/ # Configuration management
├── dex/ # DEX integrations
├── execution/ # Loop execution logic
├── safety/ # Safety monitoring
├── types/ # TypeScript types
├── wallet/ # Wallet providers
└── index.ts # Main entry point
```
### Adding New Networks
Edit `src/config/networks.ts` to add new network configurations:
- Aave pool addresses
- Token addresses
- DEX router addresses
### Adding New DEX Providers
1. Create new service class implementing `IDexService`
2. Add to `src/dex/index.ts` factory function
3. Update types and configuration
## License
MIT
## Disclaimer
This tool is provided as-is for educational and research purposes. Use at your own risk. The authors are not responsible for any losses incurred from using this tool. Always test on testnets first and understand the risks involved in DeFi leverage strategies.