Add full monorepo: virtual-banker, backend, frontend, docs, scripts, deployment

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
defiQUG
2026-02-10 11:32:49 -08:00
parent aafcd913c2
commit 88bc76da91
815 changed files with 125522 additions and 264 deletions

View File

@@ -0,0 +1,159 @@
# Bridge Engine Specification
## Overview
This document specifies the bridge engine that provides cross-chain asset transfers using CCIP and third-party bridge providers.
## Provider Abstraction
### Bridge Providers
**CCIP**: Chainlink CCIP (primary for supported chains)
**Third-Party**:
- Stargate
- Hop Protocol
- Across Protocol
- Others as needed
### Provider Interface
```typescript
interface BridgeProvider {
getName(): string;
getSupportedChains(): number[];
getQuote(request: BridgeQuoteRequest): Promise<BridgeQuote>;
executeBridge(request: BridgeRequest): Promise<Transaction>;
getStatus(txHash: string): Promise<BridgeStatus>;
}
```
## Quote Comparison
### Quote Structure
```json
{
"provider": "CCIP",
"from_chain": 138,
"to_chain": 1,
"from_token": "0x...",
"to_token": "0x...",
"amount_in": "1000000000000000000",
"amount_out": "990000000000000000",
"fee": "10000000000000000",
"estimated_time": 300, // seconds
"trust_score": 0.95,
"route": {
"steps": [...]
}
}
```
### Comparison Factors
**1. Fees**: Lower is better
**2. ETA**: Faster is better
**3. Trust Score**: Higher is better (security, audits, track record)
**4. Liquidity**: Sufficient liquidity available
**5. Supported Amounts**: Amount within limits
### Trust Scores
**Factors**:
- Security audits
- Total value locked (TVL)
- Incident history
- Team reputation
- Code maturity
## CCIP Routing Integration
### CCIP as Primary
**When to Use**: Chains supported by CCIP
**Benefits**: Secure, audited, Chainlink-backed
### CCIP Quote Flow
1. Check CCIP router for quote
2. Calculate fees (message fee + token fee)
3. Estimate execution time
4. Return quote
### CCIP Execution
1. Approve token spending (if needed)
2. Call CCIP router send function
3. Monitor source transaction
4. Track CCIP message
5. Monitor destination execution
## Failover Routing
### Strategy
**Priority Order**:
1. CCIP (if available and competitive)
2. Trusted third-party bridges
3. Alternative routes
### Failover Triggers
- CCIP unavailable
- CCIP quote significantly worse
- User preference
- Amount limits exceeded
## Proof and Receipt Tracking
### Tracking Flow
1. Store source transaction hash
2. Monitor CCIP message status
3. Link to destination transaction
4. Track execution status
5. Provide end-to-end visibility
### Status Updates
**States**:
- `pending`: Source transaction pending
- `sent`: Message sent to CCIP
- `delivered`: Message delivered
- `executing`: Executing on destination
- `completed`: Bridge completed
- `failed`: Bridge failed
## API Endpoints
### Get Bridge Quote
`GET /api/v1/bridge/quote`
**Parameters**:
- `from_chain`: Source chain ID
- `to_chain`: Destination chain ID
- `from_token`: Source token address
- `to_token`: Destination token address
- `amount`: Amount to bridge
**Response**: Best quote from all providers
### Execute Bridge
`POST /api/v1/bridge/execute`
**Body**: Bridge request parameters
**Response**: Source transaction hash
### Get Bridge Status
`GET /api/v1/bridge/status/{tx_hash}`
**Response**: Bridge status with source and destination transaction details
## References
- CCIP Tracking: See `../ccip/ccip-tracking.md`
- Wallet Connectivity: See `wallet-connectivity.md`

View File

@@ -0,0 +1,179 @@
# Safety Controls Specification
## Overview
This document specifies safety controls including phishing detection, contract risk scoring, address screening, and transaction simulation warnings.
## Phishing/Contract Risk Scoring
### Risk Factors
**1. Contract Verification**:
- Unverified: Higher risk
- Verified: Lower risk
**2. Reputation**:
- Known malicious addresses: High risk
- Known legitimate addresses: Low risk
- Unknown: Medium risk
**3. Code Analysis**:
- Suspicious functions (self-destruct, delegatecall abuse)
- Honeypot patterns
- Proxy contracts (verify implementation)
**4. Historical Data**:
- Previous scam reports
- User reports
- Security audit results
### Risk Score
**Calculation**:
```
risk_score = (verification_risk * 0.3) +
(reputation_risk * 0.3) +
(code_risk * 0.2) +
(historical_risk * 0.2)
```
**Score Ranges**:
- 0.0-0.3: Low risk (green)
- 0.3-0.6: Medium risk (yellow)
- 0.6-1.0: High risk (red)
## Address Screening
### Screening Sources
**1. Blocklists**:
- Known scam addresses
- Phishing addresses
- Mixer/tumbler addresses
**2. Reputation Services**:
- Etherscan labels
- Community reports
- Security databases
**3. Pattern Detection**:
- Address similarity (homoglyph attacks)
- Known scam patterns
### Screening Result
```json
{
"address": "0x...",
"risk_level": "high",
"reasons": [
"Address on known phishing list",
"Unverified contract",
"Suspicious transaction patterns"
],
"sources": ["etherscan", "community_reports"],
"confidence": 0.95
}
```
## Transaction Simulation and Warnings
### Simulation Checks
**1. Balance Checks**:
- Sufficient token balance
- Sufficient native balance for gas
**2. Approval Checks**:
- Current allowance
- Approval amount vs transaction amount
**3. State Changes**:
- Simulate transaction
- Detect unexpected state changes
- Check for reentrancy risks
**4. Token Transfers**:
- Unexpected token transfers
- High-value transfers
- Transfers to unknown addresses
### Warning Types
**Critical Warnings** (Block transaction):
- Insufficient balance
- Contract self-destruct
- Known malicious address
**High Warnings** (Strong recommendation to cancel):
- Unverified contract
- High slippage
- Large value transfer to new address
**Medium Warnings** (Informational):
- First interaction with contract
- Unusual transaction pattern
- High gas cost
### Warning Display
**UI Elements**:
- Warning banner with risk level
- Detailed explanation
- Option to proceed or cancel
- Educational content
## User Consent Workflow
### Consent Steps
**1. Transaction Review**:
- Display transaction details
- Show risk assessment
- Highlight warnings
**2. Confirmation**:
- User acknowledges risks
- Explicit confirmation required
- Optional: Additional confirmation for high-risk
**3. Execution**:
- Proceed with transaction
- Log consent for audit
### Consent Logging
**Fields**:
- Transaction hash
- User address
- Risk level
- Warnings shown
- Consent timestamp
- User acknowledgment
## Integration Points
### Transaction Flow Integration
1. User initiates transaction
2. Screen address/contract
3. Simulate transaction
4. Calculate risk score
5. Display warnings
6. Request consent
7. Execute if approved
### API Integration
**Risk Assessment API**:
`POST /api/v1/safety/assess`
**Request**: Transaction details
**Response**: Risk score and warnings
## References
- Swap Engine: See `swap-engine.md`
- Bridge Engine: See `bridge-engine.md`
- Security: See `../security/security-architecture.md`

View File

@@ -0,0 +1,181 @@
# Swap Engine Specification
## Overview
This document specifies the swap engine that integrates with DEX aggregators to provide optimal swap routing and execution.
## DEX Aggregator Integration
### Supported Aggregators
**1inch**: 1inch API
**0x**: 0x API
**Paraswap**: Paraswap API
**Others**: Additional aggregators as needed
### Integration Pattern
**Abstraction Layer**:
- Unified interface for all aggregators
- Quote comparison
- Best route selection
## Quote Comparison
### Quote Structure
```json
{
"from_token": "0x...",
"to_token": "0x...",
"amount_in": "1000000000000000000",
"amount_out": "2000000000000000000",
"routes": [
{
"protocol": "Uniswap V3",
"portion": 0.6
},
{
"protocol": "Curve",
"portion": 0.4
}
],
"gas_estimate": 150000,
"slippage": 0.005,
"price_impact": 0.01
}
```
### Comparison Algorithm
**Factors**:
1. **Output Amount**: Higher is better
2. **Gas Cost**: Lower is better
3. **Slippage**: Lower is better
4. **Price Impact**: Lower is better
5. **Execution Time**: Faster is better
**Scoring**:
```
score = (output_amount * 0.5) - (gas_cost * 0.2) - (slippage * 0.2) - (price_impact * 0.1)
```
## Routing Optimization
### Multi-Path Routing
**Strategy**: Split trade across multiple DEXs for better rates
**Implementation**:
- Get quotes from multiple aggregators
- Compare split vs single-path routes
- Select optimal route
### Slippage Calculation
**Formula**: `(expected_output - actual_output) / expected_output`
**Protection**:
- User-specified slippage tolerance
- Default: 0.5% (0.005)
- Warn if slippage high
## Approval Management
### Token Approvals
**Process**:
1. Check current allowance
2. Request approval if needed
3. Wait for approval confirmation
4. Execute swap
### Approval Optimization
**Strategies**:
- Approve max amount (one-time approval)
- Approve exact amount (safer, more transactions)
- Use permit2 (EIP-2612) if supported
### Approval Revocation
**Feature**: Allow users to revoke approvals
**UI**: Show all active approvals
**Action**: Revoke individual or all approvals
## Transaction Simulation
### Pre-Flight Simulation
**Purpose**: Verify transaction will succeed before signing
**Checks**:
- Sufficient balance
- Sufficient allowance
- Valid route
- Price impact within limits
- Gas estimation
### Simulation Result
```json
{
"success": true,
"simulated_output": "2000000000000000000",
"gas_estimate": 150000,
"warnings": [],
"errors": []
}
```
## Execution
### Transaction Building
**Steps**:
1. Get best quote
2. Build transaction with aggregator
3. Simulate transaction
4. Present to user for approval
5. Sign and broadcast
6. Monitor confirmation
### Error Handling
**Errors**:
- Insufficient balance
- Insufficient allowance
- Slippage exceeded
- Route failure
**Recovery**:
- Retry with adjusted parameters
- Suggest alternative routes
- Provide error explanations
## API Endpoints
### Get Quote
`GET /api/v1/swap/quote`
**Parameters**:
- `from_token`: Source token address
- `to_token`: Destination token address
- `amount_in`: Input amount
- `slippage`: Slippage tolerance (optional)
**Response**: Best quote with route details
### Execute Swap
`POST /api/v1/swap/execute`
**Body**: Transaction parameters
**Response**: Transaction hash
## References
- Wallet Connectivity: See `wallet-connectivity.md`
- Safety Controls: See `safety-controls.md`

View File

@@ -0,0 +1,116 @@
# Wallet Connectivity Specification
## Overview
This document specifies wallet connectivity options including WalletConnect v2, hardware wallet support, and embedded wallet architecture.
## WalletConnect v2 Integration
### Implementation
**Library**: `@walletconnect/web3wallet` or `@web3modal/wagmi`
**Features**:
- Multi-wallet support
- Session management
- Chain switching
- Transaction signing
- Message signing
### Connection Flow
1. User initiates connection
2. QR code displayed or deep link generated
3. User approves in wallet app
4. Session established
5. Ready for transactions
### Session Management
**Storage**: Persist sessions in localStorage
**Expiration**: Handle session expiration gracefully
**Reconnection**: Auto-reconnect on page reload
## Hardware Wallet Support
### Supported Wallets
**Ledger**: Via Ledger Live or browser extension
**Trezor**: Via Trezor Connect
**Other**: Via Web3 provider standard
### Integration
**Method**: Use Web3 provider interface
**Security**: Never expose private keys
**UX**: Clear instructions for hardware wallet usage
## Embedded Wallet
### Architecture
**Options**:
1. **Non-Custodial**: User controls keys (Web3Auth, Magic)
2. **Custodial**: Platform manages keys (Fireblocks, Circle)
**Recommendation**: Start with non-custodial, add custodial for banking features
### Non-Custodial Embedded Wallet
**Technology**: Web3Auth or similar
**Features**:
- Social login (Google, Twitter, etc.)
- Passwordless authentication
- Key management via MPC or smart contract wallets
- Recovery options
### Custodial Embedded Wallet
**Use Cases**: Banking features requiring custody
**Requirements**:
- Regulatory compliance
- Secure key storage (HSM)
- Insurance
- Audit trails
**Policy Gating**: Only enable for users meeting compliance requirements
## Key Management
### Non-Custodial Keys
**Storage**: User's device or MPC network
**Recovery**: Social recovery or seed phrase
**Security**: Never transmitted to server
### Custodial Keys
**Storage**: Hardware Security Module (HSM)
**Access**: Multi-signature approval
**Audit**: All key operations logged
## API Integration
### Wallet Connection
**Methods**:
- `connect()`: Initiate connection
- `disconnect()`: Close connection
- `getAccount()`: Get connected account
- `switchChain()`: Switch to different chain
### Transaction Signing
**Flow**:
1. Build transaction
2. Request user approval
3. Sign transaction
4. Broadcast transaction
5. Monitor confirmation
## References
- Swap Engine: See `swap-engine.md`
- Bridge Engine: See `bridge-engine.md`
- Security: See `../security/security-architecture.md`