Files
defi-arbitrage/README_SUBMODULE.md

605 lines
16 KiB
Markdown
Raw Permalink Normal View History

Initial commit: Deal orchestration tool - Freeze-resistant arbitrage loop - Implemented complete arbitrage loop (Steps 0-4) - Risk control service with hard caps (30% LTV, 25% USDTz exposure) - Progressive redemption testing (0k → 50k → cd /home/intlc/projects/proxmox/dbis_core/src/core/defi/arbitrage && git commit -m "Initial commit: Deal orchestration tool - Freeze-resistant arbitrage loop - Implemented complete arbitrage loop (Steps 0-4) - Risk control service with hard caps (30% LTV, 25% USDTz exposure) - Progressive redemption testing ($50k → $250k → $1M+) - Graceful failure handling and state management - CLI interface and programmatic API - Comprehensive documentation Features: - Capital split into three buckets (Core ETH, Working Liquidity, Opportunistic) - ETH wrapping and collateral supply - USDT borrowing at controlled LTV - Discount arbitrage execution - Partial monetization with redemption testing - Loop closing with profit capture Design Principles: - One-way risk only - Anchor asset (ETH) untouchable - No leverage on discounted assets - Independent leg settlement"M+) - Graceful failure handling and state management - CLI interface and programmatic API - Comprehensive documentation Features: - Capital split into three buckets (Core ETH, Working Liquidity, Opportunistic) - ETH wrapping and collateral supply - USDT borrowing at controlled LTV - Discount arbitrage execution - Partial monetization with redemption testing - Loop closing with profit capture Design Principles: - One-way risk only - Anchor asset (ETH) untouchable - No leverage on discounted assets - Independent leg settlement
2026-01-27 14:45:19 -08:00
# Deal Orchestration Tool - Arbitrage Module
**Freeze-Resistant, Capital-Preserving Arbitrage Loop**
This module implements a sophisticated deal orchestration tool designed to execute freeze-resistant arbitrage loops that preserve capital even when individual legs fail. The system is built on four non-negotiable design principles that ensure no single leg failure can trap principal.
## 📋 Table of Contents
- [Overview](#overview)
- [Design Principles](#design-principles)
- [Architecture](#architecture)
- [The Arbitrage Loop](#the-arbitrage-loop)
- [Risk Controls](#risk-controls)
- [Implementation Details](#implementation-details)
- [Usage](#usage)
- [Configuration](#configuration)
- [Failure Scenarios](#failure-scenarios)
- [Development](#development)
---
## Overview
This tool executes a multi-step arbitrage loop using:
- **ETH/WETH** as the anchor asset (never touched in risky operations)
- **USDT/cUSDT** as working capital (borrowed against ETH collateral)
- **USDTz** as discounted upside (bought at 40% discount, never leveraged)
The loop is designed so that if any single leg fails (redemption freezes, borrow market freezes, network congestion), the system degrades gracefully into a holding state rather than causing losses.
### Key Features
**One-Way Risk**: Principal recovery never depends on redemption
**Anchor Protection**: Core ETH remains untouched
**No Leverage on Discounted Assets**: USDTz never used as collateral
**Independent Settlement**: Each leg can settle independently
**Progressive Testing**: Redemption tested incrementally ($50k → $250k → $1M+)
**Hard Risk Caps**: 30% max LTV, 25% max USDTz exposure
---
## Design Principles
### Rule 1 — One-Way Risk Only
- You never **need** redemption to recover principal
- Redemption = upside, not survival
- Principal is protected by ETH collateral
### Rule 2 — Anchor Asset is Untouchable
- ETH / WETH is the anchor
- Stables are temporary instruments
- Core ETH bucket (50%) is never touched
### Rule 3 — Discounted Assets Never Carry Leverage
- USDTz bought at 40% discount is **never borrowed against**
- It never collateralizes anything critical
- No rehypothecation allowed
### Rule 4 — Every Leg Can Settle Independently
- No atomic dependency across chains or issuers
- If one leg freezes, loop degrades into a **holding**, not a loss
- Each step can complete independently
---
## Architecture
### File Structure
```
arbitrage/
├── types.ts # Type definitions and interfaces
├── config.ts # ChainID 138 addresses and risk params
├── risk-control.service.ts # Risk validation and enforcement
├── step-execution.service.ts # Individual step implementations
├── redemption-test.service.ts # Progressive redemption testing
├── deal-orchestrator.service.ts # Main orchestrator
├── cli.ts # Command-line interface
├── index.ts # Main exports
└── README.md # This file
```
### Core Services
#### `RiskControlService`
- Validates deal requests against risk parameters
- Enforces LTV compliance (max 30%)
- Checks USDTz exposure limits (max 25% NAV)
- Validates no rehypothecation
#### `StepExecutionService`
- **Step 0**: Capital split into three buckets
- **Step 1**: Generate working liquidity (wrap, supply, borrow)
- **Step 2**: Execute discount arbitrage (buy USDTz)
- **Step 3**: Partial monetization (split and attempt redemption)
- **Step 4**: Close the loop (repay, unlock, capture profit)
#### `RedemptionTestService`
- Progressive testing: $50k → $250k → $1M+
- Success probability decreases with amount
- Stops testing if any test fails
#### `DealOrchestratorService`
- Orchestrates the entire loop
- Manages state transitions
- Handles errors and graceful degradation
- Tracks all risk checks and redemption tests
---
## The Arbitrage Loop
### STEP 0 — Capital Split
**Purpose**: Divide initial ETH into three strategic buckets
**Example with $10M equivalent ETH**:
| Bucket | Purpose | Amount | Percentage |
|--------|---------|--------|------------|
| A | Core ETH (never touched) | $5.0M | 50% |
| B | Working Liquidity | $3.0M | 30% |
| C | Opportunistic USDTz | $2.0M | 20% |
**Critical Constraint**: ETH **never** enters the USDTz leg directly.
**Implementation**: `StepExecutionService.executeStep0()`
---
### STEP 1 — Generate Working Liquidity (Safe)
**Purpose**: Create working capital by borrowing against ETH collateral
**Process**:
1. Wrap ETH → WETH (1:1 ratio)
2. Supply WETH to lending protocol on ChainID 138
3. Borrow USDT/cUSDT at ≤30% LTV
**Example**:
- $3M WETH collateral supplied
- $900k USDT borrowed (30% LTV)
**Safety**: If anything freezes later, ETH is recoverable due to low LTV.
**Implementation**: `StepExecutionService.executeStep1()`
**Risk Checks**:
- LTV compliance (must be ≤30%)
- Collateral value validation
---
### STEP 2 — Execute Discount Arbitrage (Isolated)
**Purpose**: Use borrowed USDT to buy discounted USDTz
**Process**:
1. Use borrowed USDT ($900k in example)
2. Buy USDTz at 40% discount
3. Receive ≈ $1.5M USDTz (at 40% discount: $900k / 0.6 = $1.5M)
**Critical Rules**:
- This USDTz is **never pledged** as collateral
- Never bridged unless tested small first
- Treated as optional upside, not money
**Implementation**: `StepExecutionService.executeStep2()`
**Risk Checks**:
- USDTz exposure limit (must be <25% of total NAV)
- No rehypothecation validation
---
### STEP 3 — Partial Monetization (Optional, Safe)
**Purpose**: Attempt to monetize a portion of USDTz while holding the rest
**Process**:
1. Split USDTz into two portions:
- **30-40%**: Attempt redemption/swap to USDT
- **60-70%**: Hold cold as optional upside
2. Progressive redemption testing:
- Test $50k first (95% success probability)
- Then $250k (85% success probability)
- Then $1M+ (75% success probability)
3. If redemption works:
- Convert to USDT
- Ready to repay borrow
- Capture spread
4. If redemption freezes:
- Nothing upstream is affected
- ETH collateral remains safe
- Loan remains healthy
- USDTz held as optional upside
**Implementation**: `StepExecutionService.executeStep3()` + `RedemptionTestService`
---
### STEP 4 — Close the Loop (If Redemption Works)
**Purpose**: Complete the arbitrage by repaying borrow and unlocking collateral
**Process** (if 40% redeems successfully):
1. $600k USDTz → $600k USDT (from redemption)
2. Repay $900k borrow (may need additional liquidity or wait for more redemption)
3. Residual ETH unlocked
4. Remaining USDTz ($900k) is pure upside
**Profit Sources**:
- Discount capture (40% on USDTz)
- ETH appreciation (if ETH price increases)
- Interest spread (if borrowing rate < redemption yield)
**Implementation**: `StepExecutionService.executeStep4()`
**Note**: If redemption fails, this step is skipped and the deal remains in "frozen" state.
---
## Risk Controls
### Hard Caps
| Control | Limit | Enforcement |
|---------|-------|-------------|
| **Max LTV** | 30% | Validated before and after borrowing |
| **Max USDTz Exposure** | <25% of total NAV | Checked after USDTz acquisition |
| **No Rehypothecation** | USDTz cannot be collateral | Validated throughout execution |
### Redemption Testing
Progressive testing ensures redemption throughput is verified before committing large amounts:
1. **$50k test** (95% success probability)
- Small test to verify basic functionality
- If fails, stop immediately
2. **$250k test** (85% success probability)
- Medium test to verify scaling
- Cumulative: $300k tested
3. **$1M+ test** (75% success probability)
- Large test to verify production capacity
- Cumulative: $1.3M+ tested
**Implementation**: `RedemptionTestService.executeProgressiveTests()`
---
## Implementation Details
### Type System
All types are defined in `types.ts`:
- `DealExecutionRequest`: Input parameters for deal execution
- `DealState`: Current state of a deal (step, buckets, amounts, tx hashes)
- `DealStep`: Enum of possible deal steps
- `Step0Result` through `Step4Result`: Results from each step
- `RiskCheckResult`: Risk validation results
- `RedemptionTestResult`: Individual redemption test results
- `DealExecutionResult`: Complete execution result
### State Management
Deals progress through states:
1. `INITIALIZED` → Deal created
2. `CAPITAL_SPLIT` → Step 0 complete
3. `WORKING_LIQUIDITY_GENERATED` → Step 1 complete
4. `ARBITRAGE_EXECUTED` → Step 2 complete
5. `MONETIZATION_ATTEMPTED` → Step 3 complete
6. `LOOP_CLOSED` → Step 4 complete (success)
7. `FROZEN` → Redemption failed, holding state
8. `FAILED` → Error occurred
### Error Handling
- **Graceful Degradation**: Failures in optional steps (redemption) don't affect core positions
- **Risk Validation**: All steps validated before execution
- **Transaction Tracking**: All on-chain transactions tracked with hashes
- **Error Logging**: Comprehensive logging via Winston
### Integration Points
The tool integrates with:
- **Prisma ORM**: For database persistence (when implemented)
- **Winston Logger**: For structured logging
- **Existing DeFi Services**: Follows patterns from `DeFiSwapService`
- **ChainID 138**: All operations on ChainID 138 network
---
## Usage
### Command-Line Interface
```bash
# Basic execution
node cli.js execute \
--totalEthValue 10000000 \
--participantBankId BANK001 \
--moduleId MODULE001
# With custom parameters
node cli.js execute \
--totalEthValue 10000000 \
--participantBankId BANK001 \
--moduleId MODULE001 \
--usdtzDiscount 0.40 \
--maxLtv 0.30 \
--redemptionPortion 0.35 \
--coldStoragePortion 0.65
```
### Programmatic API
```typescript
import { dealOrchestratorService } from '@/core/defi/arbitrage';
import { DealExecutionRequest } from '@/core/defi/arbitrage/types';
const request: DealExecutionRequest = {
totalEthValue: '10000000', // $10M
participantBankId: 'BANK001',
moduleId: 'MODULE001',
usdtzDiscountRate: 0.40, // 40% discount
maxLtv: 0.30, // 30% LTV
monetizationSplit: {
redemptionPortion: 0.35, // 35% for redemption
coldStoragePortion: 0.65, // 65% for cold storage
},
};
const result = await dealOrchestratorService.executeDeal(request);
console.log('Deal ID:', result.dealId);
console.log('Status:', result.status);
console.log('Step:', result.state.step);
console.log('Final Profit:', result.finalProfit?.toString());
// Check risk compliance
const allRiskChecksPassed = result.riskChecks.every(r => r.passed);
console.log('All Risk Checks Passed:', allRiskChecksPassed);
// Check redemption tests
const redemptionReliable = result.redemptionTests.every(r => r.successful);
console.log('Redemption Reliable:', redemptionReliable);
```
### Service-Level Usage
```typescript
// Use individual services
import {
riskControlService,
stepExecutionService,
redemptionTestService,
} from '@/core/defi/arbitrage';
// Validate a deal request
const riskCheck = await riskControlService.validateDealRequest(
request,
new Decimal('10000000')
);
// Execute a specific step
const step0Result = await stepExecutionService.executeStep0(request);
// Test redemption
const testResults = await redemptionTestService.executeProgressiveTests(
new Decimal('1500000')
);
```
---
## Configuration
### Environment Variables
Set these environment variables for protocol addresses:
```bash
# RPC Configuration
export CHAIN138_RPC_URL="http://192.168.11.250:8545"
# or
export CHAIN138_RPC_URL="https://rpc-core.d-bis.org"
# Protocol Addresses (to be configured based on actual deployment)
export CHAIN138_LENDING_PROTOCOL="<lending-protocol-address>"
export CHAIN138_VAULT_ADDRESS="<vault-contract-address>"
export CHAIN138_LEDGER_ADDRESS="<ledger-contract-address>"
export CHAIN138_USDTZ_SWAP_ADDRESS="<usdtz-swap-contract-address>"
export CHAIN138_USDTZ_REDEEM_ADDRESS="<usdtz-redeem-contract-address>"
```
### Token Addresses (ChainID 138)
Pre-configured in `config.ts`:
| Token | Address | Decimals |
|-------|---------|----------|
| **WETH** | `0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2` | 18 |
| **WETH10** | `0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f` | 18 |
| **LINK** | `0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03` | 18 |
| **cUSDT** | `0x93E66202A11B1772E55407B32B44e5Cd8eda7f22` | 6 |
| **cUSDC** | `0xf22258f57794CC8E06237084b353Ab30fFfa640b` | 6 |
### Risk Parameters
Default values in `config.ts`:
```typescript
DEFAULT_RISK_PARAMS = {
MAX_LTV: 0.30, // 30% maximum
MAX_USDTZ_EXPOSURE_PCT: 0.25, // 25% of NAV
DEFAULT_USDTZ_DISCOUNT: 0.40, // 40% discount
DEFAULT_MONETIZATION_SPLIT: {
redemptionPortion: 0.35, // 35% for redemption
coldStoragePortion: 0.65, // 65% for cold storage
},
}
```
### Capital Split Defaults
```typescript
DEFAULT_CAPITAL_SPLIT = {
coreEthPct: 0.50, // 50% core ETH
workingLiquidityPct: 0.30, // 30% working liquidity
opportunisticUsdtzPct: 0.20, // 20% opportunistic
}
```
---
## Failure Scenarios
### Failure Case A — USDTz Redemption Freezes
**What Happens**:
- ✅ ETH collateral untouched
- ✅ Loan still healthy (low LTV)
- ✅ USDTz just sits as optional upside
- ❌ No liquidation
- ❌ No margin calls
**System Response**:
- Deal state transitions to `FROZEN`
- No upstream impact
- Can wait indefinitely or attempt redemption later
**Implementation**: Handled in `StepExecutionService.executeStep3()`
---
### Failure Case B — USDT Borrow Market Freezes
**What Happens**:
- ✅ ETH collateral still priced
- ✅ LTV low enough to wait (30% max)
- ✅ No forced unwind
**System Response**:
- Can wait for market to recover
- Can repay from other liquidity sources
- Can refinance later
**Implementation**: Low LTV ensures safety margin
---
### Failure Case C — ChainID 138 Congestion
**What Happens**:
- ✅ ETH is base layer or wrapped (no cross-chain dependency)
- ✅ No issuer dependency
- ✅ No atomic cross-chain operations
**System Response**:
- Operations can wait for network to clear
- No time-sensitive atomic dependencies
- Each leg can complete independently
---
## Development
### Prerequisites
- TypeScript 4.5+
- Node.js 16+
- Prisma ORM (for database integration)
- Winston (for logging)
- Decimal.js (for precise decimal arithmetic)
### Dependencies
```json
{
"@prisma/client": "^5.0.0",
"decimal.js": "^10.4.0",
"uuid": "^9.0.0",
"winston": "^3.11.0"
}
```
### Building
```bash
cd dbis_core/src/core/defi/arbitrage
tsc --build
```
### Testing
```bash
# Run tests (when test suite is implemented)
npm test
# Run with coverage
npm run test:coverage
```
### Integration with Existing Services
The tool follows patterns from existing `DeFiSwapService`:
- Uses Prisma for database operations
- Uses Winston for logging
- Uses Decimal.js for financial calculations
- Follows TypeScript path aliases (`@/core/*`)
### Future Enhancements
1. **On-Chain Integration**: Replace mock transactions with actual smart contract calls
2. **Database Persistence**: Store deal states in Prisma database
3. **Monitoring**: Add metrics and alerting
4. **API Endpoints**: REST/GraphQL API for deal management
5. **WebSocket Updates**: Real-time deal status updates
6. **Multi-Chain Support**: Extend to other chains beyond ChainID 138
---
## Notes
### Why This Loop Cannot Blow Up
The loop **cannot blow up** unless:
1. ETH itself collapses (systemic risk, not loop-specific)
2. LTV discipline is violated (prevented by hard caps)
Everything else becomes a **timing issue**, not a solvency issue.
### USDTz Treatment
USDTz is treated as:
> **A deeply discounted call option, not money**
This means:
- Never used as critical collateral
- Never required for principal recovery
- Always optional upside
- Can be held indefinitely if redemption freezes
### Capital Preservation
The system is designed for capital preservation:
- Core ETH (50%) never touched
- Low LTV (30%) provides safety margin
- Independent leg settlement prevents cascade failures
- Graceful degradation to holding state
---
## License
[To be determined based on parent project license]
---
## Author
Created as part of the DBIS Core Banking System - DeFi Arbitrage Module
**Date**: January 27, 2026
**Version**: 1.0.0
---
## References
- ChainID 138 Token Addresses: `docs/11-references/CHAIN138_TOKEN_ADDRESSES.md`
- DeFi Swap Service: `dbis_core/src/core/defi/sovereign/defi-swap.service.ts`
- Vault Contract: `smom-dbis-138/contracts/vault/Vault.sol`
- Ledger Contract: `smom-dbis-138/contracts/vault/Ledger.sol`