# Credential Manager - 多平台对冲账号管理模块

A comprehensive multi-platform account management system for cryptocurrency trading with hedging capabilities.

## ✨ Features

- **🔐 Multi-Platform Signing**: Support for Pacifica (Ed25519), Aster (EIP-191), and Binance (HMAC-SHA256)
- **⚡ High Performance**: <50ms signing, <100ms hot-reload
- **🏊 Account Pool Management**: Load balancing, failover, health monitoring
- **🔄 Hot Configuration Reload**: Zero-downtime configuration updates
- **📡 Event-Driven Architecture**: Loose coupling with trading systems
- **🎯 Hedging Support**: Cross-platform account distribution and management

## 🚀 Quick Start

### 1. Basic Usage

```typescript
import { CredentialManager } from '@/core/credential-manager/CredentialManager'
import { Platform } from '@/types/credential'

// Initialize credential manager
const credentialManager = new CredentialManager()

// Load configuration
await credentialManager.loadConfiguration({
  accounts: [
    {
      id: 'pacifica-main',
      name: 'Pacifica Main Account',
      platform: Platform.PACIFICA,
      enabled: true,
      credentials: {
        type: 'ed25519',
        privateKey: 'your-hex-private-key'
      }
    }
  ]
})

// Sign a message
const message = new TextEncoder().encode('trading data')
const result = await credentialManager.sign('pacifica-main', message)

if (result.success) {
  console.log('Signature:', result.signature)
  console.log('Time taken:', result.metadata?.duration, 'ms')
}
```

### 2. Trading Integration

```typescript
import { TradingOperation } from '@/core/credential-manager/TradingIntegration'

// Sign trading request
const tradingRequest = {
  operation: TradingOperation.PLACE_ORDER,
  platform: Platform.PACIFICA,
  parameters: {
    symbol: 'SOL/USDC',
    side: 'buy',
    quantity: 100,
    type: 'market'
  }
}

const result = await credentialManager.signTradingRequest(tradingRequest)
// Returns platform-specific signature format ready for API submission
```

### 3. Hedging Operations

```typescript
// Cross-platform hedging
const platforms = [Platform.PACIFICA, Platform.ASTER, Platform.BINANCE]
const distribution = await credentialManager.getHedgingAccountDistribution(
  500000, // $500k total volume
  platforms
)

// Execute delta-neutral strategy
const hedgeTrades = [
  { operation: TradingOperation.PLACE_ORDER, platform: Platform.PACIFICA, /* ... */ },
  { operation: TradingOperation.PLACE_ORDER, platform: Platform.ASTER, /* ... */ },
  { operation: TradingOperation.PLACE_ORDER, platform: Platform.BINANCE, /* ... */ }
]

const results = await credentialManager.signBatchTradingRequests(hedgeTrades)
```

## 📋 Configuration

### Complete Configuration Example

```json
{
  "accounts": [
    {
      "id": "pacifica-main",
      "name": "Pacifica Main Trading Account",
      "platform": "PACIFICA",
      "enabled": true,
      "credentials": {
        "type": "ed25519",
        "privateKey": "f26670e2ca334117f8859f9f32e50251641953a30b54f6ffcf82db836cfdfea5"
      }
    },
    {
      "id": "aster-main",
      "name": "Aster Main Account",
      "platform": "ASTER",
      "enabled": true,
      "credentials": {
        "type": "secp256k1",
        "privateKey": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
      }
    },
    {
      "id": "binance-spot",
      "name": "Binance Spot Trading",
      "platform": "BINANCE",
      "enabled": true,
      "credentials": {
        "type": "hmac",
        "apiKey": "your-binance-api-key",
        "secretKey": "your-binance-secret-key"
      }
    }
  ],
  "hedging": {
    "platforms": {
      "PACIFICA": {
        "enabled": true,
        "primaryAccounts": ["pacifica-main"],
        "backupAccounts": ["pacifica-backup"],
        "loadBalanceStrategy": "round-robin",
        "healthCheckInterval": 30000,
        "failoverThreshold": 3
      },
      "ASTER": {
        "enabled": true,
        "primaryAccounts": ["aster-main"],
        "backupAccounts": [],
        "loadBalanceStrategy": "weighted",
        "healthCheckInterval": 30000,
        "failoverThreshold": 2
      },
      "BINANCE": {
        "enabled": true,
        "primaryAccounts": ["binance-spot"],
        "backupAccounts": [],
        "loadBalanceStrategy": "least-used",
        "healthCheckInterval": 15000,
        "failoverThreshold": 2
      }
    },
    "hedging": {
      "enableCrossplatformBalancing": true,
      "maxAccountsPerPlatform": 10,
      "reservationTimeoutMs": 60000
    }
  }
}
```

### Load Balancing Strategies

- **round-robin**: Evenly distribute requests across accounts
- **weighted**: Account selection based on health scores
- **least-used**: Prefer accounts with lowest recent usage
- **random**: Random selection from available accounts

## 🔐 Supported Platforms

### Pacifica (Solana-based DEX)
- **Algorithm**: Ed25519
- **Key Format**: 64-character hex string
- **Signature Format**: Base64
- **Performance**: ~2-5ms per signature

```typescript
credentials: {
  type: 'ed25519',
  privateKey: 'f26670e2ca334117f8859f9f32e50251641953a30b54f6ffcf82db836cfdfea5'
}
```

### Aster (Ethereum-compatible)
- **Algorithm**: EIP-191 Personal Message Signing
- **Key Format**: 0x-prefixed hex string (64 chars)
- **Signature Format**: 0x-prefixed hex (130 chars)
- **Performance**: ~10-20ms per signature

```typescript
credentials: {
  type: 'secp256k1',
  privateKey: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'
}
```

### Binance (Centralized Exchange)
- **Algorithm**: HMAC-SHA256
- **Credentials**: API Key + Secret Key
- **Signature Format**: 64-character hex string
- **Performance**: ~1-3ms per signature

```typescript
credentials: {
  type: 'hmac',
  apiKey: 'your-binance-api-key',
  secretKey: 'your-binance-secret-key'
}
```

## 🏥 Health Monitoring

The credential manager automatically monitors account health:

```typescript
// Check account health
const healthStatuses = await credentialManager.checkAccountHealth(['account-1', 'account-2'])

healthStatuses.forEach((status, accountId) => {
  console.log(`${accountId}: Health ${status.healthScore} (${status.consecutiveFailures} failures)`)
})

// Update account status after trading
await credentialManager.updateAccountAfterTrade('account-1', {
  success: true,
  tradeId: 'trade-123',
  executedPrice: 120.5,
  timestamp: new Date()
})
```

## 📡 Event System

Subscribe to real-time events:

```typescript
// Subscribe to account events
const unsubscribe = credentialManager.subscribeToAccountEvents((event) => {
  console.log(`Account ${event.accountId} on ${event.platform}:`, event)
})

// Subscribe to signing events
credentialManager.subscribeToSigningEvents((event) => {
  if (event.success) {
    console.log(`Signing success: ${event.duration}ms`)
  } else {
    console.log(`Signing failed: ${event.error}`)
  }
})
```

## 🔄 Hot Configuration Reload

The credential manager supports hot-reloading configuration files:

```typescript
// Enable file watching
await credentialManager.loadConfigurationFromFile('config/accounts.json', {
  enableHotReload: true,
  watchDebounceMs: 100
})

// Configuration changes are automatically applied within 100ms
// Service remains available during updates
```

## 🎯 Account Reservation

Reserve accounts for complex trading strategies:

```typescript
// Reserve accounts for 30 seconds
const reservation = await credentialManager.reserveAccountsForTrading(
  ['pacifica-main', 'aster-main'],
  30000
)

if (reservation.success) {
  // Execute complex trading strategy
  // Reserved accounts won't be used by other operations

  // Release when done
  await credentialManager.releaseReservedAccounts(['pacifica-main', 'aster-main'])
}
```

## ⚡ Performance

- **Signing Speed**: <50ms (typically 2-20ms depending on platform)
- **Hot-Reload**: <100ms configuration updates
- **Concurrent Operations**: Supports 100+ concurrent accounts
- **Memory Efficient**: Minimal memory footprint
- **High Throughput**: Optimized for high-frequency trading

## 🧪 Testing

Run the demo to see it in action:

```bash
# Quick demo
npx tsx scripts/run-credential-manager-demo.ts

# Full demo with all features
npx tsx src/examples/credential-manager-demo.ts

# Run tests
npm test -- --testPathPattern=credential-manager
```

## 🔧 API Reference

### Core Classes

- **`CredentialManager`**: Main service coordinator
- **`UnifiedSigner`**: Cross-platform signing service
- **`HedgingAccountPool`**: Account pool management
- **`AccountStatus`**: Health monitoring
- **`ConfigLoader`**: Configuration management

### Platform Signers

- **`PacificaSigner`**: Ed25519 signing for Solana/Pacifica
- **`AsterSigner`**: EIP-191 signing for Ethereum-compatible chains
- **`BinanceSigner`**: HMAC-SHA256 signing for Binance API

### Integration Interfaces

- **`ITradingModuleIntegration`**: Trading system integration
- **`ModuleEventBus`**: Event-driven communication

## 🛡️ Security Best Practices

1. **Private Key Storage**: Store private keys securely, preferably encrypted
2. **Access Control**: Limit access to credential configuration files
3. **Key Rotation**: Regularly rotate API keys and private keys
4. **Monitoring**: Monitor for unusual signing patterns
5. **Network Security**: Use secure connections for all API calls

## 📚 Examples

See the `/examples` directory for comprehensive usage examples:

- **`credential-manager-demo.ts`**: Full feature demonstration
- **Configuration examples**: Various deployment scenarios
- **Integration patterns**: Trading system integration examples

## 🤝 Integration with Trading Systems

The credential manager is designed to integrate seamlessly with trading systems:

```typescript
// In your trading system
import { CredentialManager } from '@/core/credential-manager'

class TradingEngine {
  constructor(private credentialManager: CredentialManager) {}

  async executeHedgeStrategy() {
    // Use credential manager for signing
    const result = await this.credentialManager.signTradingRequest({
      operation: TradingOperation.PLACE_ORDER,
      platform: Platform.PACIFICA,
      parameters: { /* ... */ }
    })

    // Submit to exchange API with proper signature format
    await this.submitToExchange(result.platformSignature)
  }
}
```

## 📈 Monitoring and Metrics

Built-in performance metrics:

```typescript
const metrics = credentialManager.getMetrics()
console.log('Performance:', {
  totalOperations: metrics.totalOperations,
  successRate: metrics.successfulOperations / metrics.totalOperations,
  averageTime: metrics.averageSigningTime,
  platformBreakdown: metrics.platformBreakdown
})
```

---

For more detailed examples and advanced usage, see the demo files and test suites.