data-model.md 22 KB

数据模型设计:多平台对冲账号管理模块

特性:001-credential-manager 日期:2025-09-29 (更新) 状态:Phase 1 - 数据模型设计 用户需求:用于多平台对冲的账号管理模块,智能注入账户分辨不同平台执行对应业务

核心实体模型

1. Platform(平台)

描述:代表不同的交易平台,定义了特定的签名和认证规则。

属性

  • id: string - 平台唯一标识符
  • name: string - 平台显示名称
  • signatureType: SignatureType - 签名算法类型

枚举值

enum Platform {
  PACIFICA = 'pacifica',
  ASTER = 'aster',
  BINANCE = 'binance'
}

enum SignatureType {
  ED25519 = 'ed25519',
  ECDSA_ETHEREUM = 'ecdsa-ethereum',
  HMAC_SHA256 = 'hmac-sha256'
}

验证规则

  • id必须是有效的平台枚举值
  • name不能为空
  • signatureType必须与平台匹配

2. Account(账户)

描述:包含账户ID、平台类型、凭证信息的基本数据结构。

属性

interface Account {
  id: string;                    // 账户唯一ID
  platform: Platform;           // 所属平台
  credentials: Credentials;      // 凭证信息
  metadata?: {                   // 可选元数据
    alias?: string;              // 账户别名
    description?: string;        // 账户描述
    [key: string]: any;         // 其他自定义字段
  };
}

凭证结构

type Credentials = PacificaCredentials | AsterCredentials | BinanceCredentials;

interface PacificaCredentials {
  type: 'pacifica';
  privateKey: string;            // 64字符十六进制Ed25519私钥
}

interface AsterCredentials {
  type: 'aster';
  privateKey: string;            // 以太坊格式私钥
}

interface BinanceCredentials {
  type: 'binance';
  apiKey: string;               // API密钥
  secretKey: string;            // 密钥对
}

验证规则

  • id在所有账户中必须唯一
  • platform必须是有效的Platform枚举值
  • credentials类型必须与platform匹配
  • Pacifica私钥必须是64字符十六进制字符串
  • Aster私钥必须是以太坊格式(0x前缀)
  • Binance API密钥不能为空

3. Signer(签名器)

描述:提供统一签名接口的组件,内部根据平台类型调用对应算法。

接口定义

interface Signer {
  // 统一签名接口
  sign(accountId: string, message: Uint8Array): Promise<SignResult>;

  // 验证签名
  verify(accountId: string, message: Uint8Array, signature: string): Promise<boolean>;

  // 获取账户信息
  getAccount(accountId: string): Account | null;

  // 列出所有账户
  listAccounts(): Account[];
}

interface SignResult {
  success: boolean;
  signature?: string;           // Base64编码的签名
  algorithm: string;           // 使用的签名算法
  timestamp: Date;             // 签名时间戳
  error?: string;              // 错误信息
}

平台特定签名策略

interface SignerStrategy {
  platform: Platform;
  sign(message: Uint8Array, credentials: Credentials): Promise<string>;
  verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean>;
}

4. ConfigLoader(配置加载器)

描述:负责从配置文件加载账户信息并监听文件变更。

接口定义

interface ConfigLoader {
  // 加载配置文件
  loadConfig(filePath: string): Promise<LoadResult>;

  // 开始监听文件变更
  watchConfig(filePath: string, callback: (accounts: Account[]) => void): void;

  // 停止监听
  stopWatching(): void;
}

interface LoadResult {
  success: boolean;
  accounts: Account[];
  errors?: string[];
  loadTime: number;            // 加载耗时(毫秒)
}

配置文件格式

interface ConfigFile {
  version: string;             // 配置文件版本
  accounts: AccountConfig[];
}

interface AccountConfig {
  id: string;
  platform: Platform;
  credentials: Credentials;
  metadata?: Record<string, any>;
}

对冲业务专用实体

5. HedgingAccountPool(对冲账户池)

描述:支持多平台对冲业务的账户池管理,提供负载均衡和故障转移。

属性

interface HedgingAccountPool {
  poolId: string;                       // 账户池ID
  name: string;                         // 池名称
  strategy: LoadBalanceStrategy;        // 负载均衡策略
  accounts: HedgingAccountGroup;        // 账户分组
  status: PoolStatus;                   // 池状态
  metadata: {
    description?: string;
    createdAt: Date;
    updatedAt: Date;
    owner?: string;
  };
}

interface HedgingAccountGroup {
  primary: string[];                    // 主要账户ID列表
  backup: string[];                     // 备用账户ID列表
  test: string[];                       // 测试账户ID列表
}

enum LoadBalanceStrategy {
  ROUND_ROBIN = 'round-robin',          // 轮询
  RANDOM = 'random',                    // 随机选择
  WEIGHTED = 'weighted',                // 权重分配
  LEAST_USED = 'least-used'             // 最少使用
}

enum PoolStatus {
  ACTIVE = 'active',                    // 活跃
  DEGRADED = 'degraded',                // 降级(部分账户不可用)
  INACTIVE = 'inactive'                 // 不可用
}

验证规则

  • poolId在所有账户池中必须唯一
  • primary账户列表不能为空
  • 所有账户ID必须在系统中存在
  • 不同组别可以有重叠账户(支持备用降级)

6. AccountStatus(账户状态)

描述:扩展账户状态信息,支持对冲业务实时监控。

属性

interface AccountStatus {
  accountId: string;                    // 账户ID
  platform: Platform;                  // 所属平台
  status: AccountHealth;                // 健康状态
  performance: PerformanceMetrics;      // 性能指标
  balanceInfo?: BalanceSnapshot;        // 余额快照
  lastActivity: Date;                   // 最后活动时间
  failureCount: number;                 // 失败计数
  metadata: {
    poolMembership: string[];           // 所属账户池
    priority: number;                   // 优先级 (1-10)
    maxConcurrency?: number;            // 最大并发限制
  };
}

enum AccountHealth {
  HEALTHY = 'healthy',                  // 健康
  WARNING = 'warning',                  // 警告(性能下降)
  CRITICAL = 'critical',                // 严重(频繁失败)
  OFFLINE = 'offline'                   // 离线
}

interface PerformanceMetrics {
  avgSignTime: number;                  // 平均签名时间(ms)
  successRate: number;                  // 成功率 (0-1)
  requestCount: number;                 // 请求次数
  lastResetAt: Date;                    // 指标重置时间
}

interface BalanceSnapshot {
  totalValue: number;                   // 总价值 (USD)
  positions: Record<string, number>;    // 持仓 {symbol: amount}
  lastUpdated: Date;                    // 更新时间
}

状态转换规则

  • HEALTHY → WARNING: 成功率降至95%以下
  • WARNING → CRITICAL: 成功率降至90%以下或连续失败>5次
  • CRITICAL → OFFLINE: 连续失败>10次
  • 任何状态 → HEALTHY: 成功操作且指标恢复正常

7. AccountRegistry(账户注册表)

描述:基于现有AccountRegistry模式的简化实现,避免复杂工厂适配器。

属性

interface AccountRegistry {
  // 基础账户管理
  register(account: RegisteredAccount): void;
  unregister(platform: string, accountId: string): boolean;
  getCredentials(platform: string, accountId: string): Credentials | null;
  hasAccount(platform: string, accountId: string): boolean;
  listAccounts(): Array<{platform: string; accountId: string; metadata?: any}>;

  // 对冲业务扩展
  getAccountsByPool(poolId: string): RegisteredAccount[];
  getHealthyAccounts(platform?: Platform): RegisteredAccount[];
  selectAccountForTrading(poolId: string, strategy?: LoadBalanceStrategy): RegisteredAccount | null;
  updateAccountStatus(accountId: string, status: AccountStatus): void;

  // 热加载支持
  reloadFromConfig(configPath: string): Promise<LoadResult>;
  watchConfig(configPath: string): void;
  stopWatching(): void;
}

interface RegisteredAccount {
  platform: string;
  accountId: string;
  credentials: Credentials;
  metadata?: {
    name?: string;
    description?: string;
    pools?: string[];                   // 所属账户池
    priority?: number;                  // 优先级
  };
}

设计原则

  • 遵循宪章v1.6.0简化要求,避免过度抽象
  • 调用链控制在3层以内:业务层 → AccountRegistry → 存储层
  • 直接依赖注入,不使用复杂工厂模式
  • 内存缓存优化,O(1)查找性能

实体关系图

AccountRegistry (1) ←→ (N) RegisteredAccount
    ↓                    ↓
HedgingAccountPool (1) ←→ (N) AccountStatus
    ↓                    ↓
LoadBalanceStrategy (1) ←→ (N) Account (基础)
    ↓                    ↓
Signer (1) ←→ (N) SignerStrategy
    ↓
SignerStrategy (N) ←→ (1) Platform

关系说明(简化架构)

  1. AccountRegistry管理所有RegisteredAccount(O(1)查找)
  2. HedgingAccountPool组织账户池,支持负载均衡
  3. AccountStatus实时跟踪账户健康状态
  4. Signer通过策略模式处理多平台签名
  5. 调用链: 业务层 → AccountRegistry → Signer → SignerStrategy
  6. 避免复杂工厂适配器,符合宪章v1.6.0简化要求

状态变化流程

配置文件生命周期

[文件创建] → [首次加载] → [监听变更] → [热重载] → [验证] → [更新内存]
     ↓         ↓          ↓         ↓        ↓         ↓
   CREATED → LOADING → WATCHING → RELOADING → VALIDATED → UPDATED

账户状态管理

enum AccountStatus {
  LOADING = 'loading',      // 正在加载
  ACTIVE = 'active',        // 活跃可用
  ERROR = 'error',          // 错误状态
  REMOVED = 'removed'       // 已移除
}

状态转换规则

  • LOADING → ACTIVE:凭证验证成功
  • ACTIVE → ERROR:签名失败或凭证无效
  • ANY → REMOVED:从配置文件中删除
  • ERROR → ACTIVE:问题解决后重新验证

JSON配置格式

账户配置文件结构

{
  "version": "1.0",
  "accounts": [
    {
      "id": "pacifica-main-001",
      "platform": "pacifica",
      "credentials": {
        "type": "pacifica",
        "privateKey": "abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab"
      },
      "metadata": {
        "alias": "Pacifica主账户",
        "description": "用于Pacifica交易的主要账户",
        "environment": "production"
      }
    },
    {
      "id": "binance-api-001",
      "platform": "binance",
      "credentials": {
        "type": "binance",
        "apiKey": "your_binance_api_key",
        "secretKey": "your_binance_secret_key"
      },
      "metadata": {
        "alias": "Binance API账户",
        "testnet": false
      }
    }
  ]
}

JSON Schema验证

const accountConfigSchema = {
  type: "object",
  properties: {
    version: { type: "string", pattern: "^\\d+\\.\\d+$" },
    accounts: {
      type: "array",
      items: {
        type: "object",
        properties: {
          id: { type: "string", minLength: 1 },
          platform: { enum: ["pacifica", "aster", "binance"] },
          credentials: {
            oneOf: [
              {
                properties: {
                  type: { const: "pacifica" },
                  privateKey: {
                    type: "string",
                    pattern: "^[0-9a-fA-F]{64}$"
                  }
                },
                required: ["type", "privateKey"]
              },
              {
                properties: {
                  type: { const: "binance" },
                  apiKey: { type: "string", minLength: 1 },
                  secretKey: { type: "string", minLength: 1 }
                },
                required: ["type", "apiKey", "secretKey"]
              }
              // 其他平台schema...
            ]
          }
        },
        required: ["id", "platform", "credentials"]
      }
    }
  },
  required: ["version", "accounts"]
};

性能要求映射

实体 性能要求 实现策略
ConfigLoader 加载<100ms 异步文件读取 + JSON解析优化
Signer 签名<50ms 内存缓存凭证 + 高性能签名库
Account 查询<10ms 内存索引 + HashMap查找
Platform识别 识别<1ms 正则表达式预编译 + 优先级队列

错误处理模型

错误分类

enum ErrorType {
  CONFIG_LOAD_ERROR = 'config_load_error',
  VALIDATION_ERROR = 'validation_error',
  SIGNATURE_ERROR = 'signature_error',
  PLATFORM_DETECTION_ERROR = 'platform_detection_error'
}

interface CredentialError {
  type: ErrorType;
  message: string;
  accountId?: string;
  timestamp: Date;
  details?: any;
}

错误处理策略

  • 配置加载错误:记录错误,跳过无效账户,继续加载其他账户
  • 验证错误:标记账户为ERROR状态,不影响其他账户
  • 签名错误:返回错误结果,记录日志,不影响后续操作
  • 平台识别错误:使用默认策略或手动指定平台

模块间交互接口设计

8. TradingModuleIntegration(交易模块集成)

描述:提供与交易模块、风控模块、监控模块等的标准化交互接口。

属性

interface TradingModuleIntegration {
  // 为交易模块提供签名服务
  signTradingRequest(request: TradingSignRequest): Promise<TradingSignResponse>;

  // 批量签名支持(高频交易场景)
  signBatchTradingRequests(requests: TradingSignRequest[]): Promise<TradingSignResponse[]>;

  // 账户状态查询(供交易模块选择可用账户)
  getAvailableAccountsForTrading(criteria: AccountSelectionCriteria): Promise<AvailableAccount[]>;

  // 实时账户健康检查
  checkAccountHealth(accountIds: string[]): Promise<Map<string, AccountHealthStatus>>;

  // 交易后更新账户状态
  updateAccountAfterTrade(accountId: string, tradeResult: TradeResult): Promise<void>;
}

interface TradingSignRequest {
  accountId: string;                    // 指定账户ID
  platform: Platform;                  // 目标平台
  orderData: OrderData;                 // 订单数据
  requestId: string;                    // 请求唯一ID(幂等性)
  timestamp: number;                    // 请求时间戳
  urgency: 'normal' | 'high' | 'critical'; // 紧急程度
}

interface OrderData {
  symbol: string;                       // 交易对
  side: 'buy' | 'sell';               // 买卖方向
  type: 'market' | 'limit' | 'stop';  // 订单类型
  quantity: number;                     // 数量
  price?: number;                       // 价格(限价单)
  timeInForce?: string;                 // 有效期
  clientOrderId?: string;               // 客户端订单ID
}

interface TradingSignResponse {
  success: boolean;
  signature?: string;                   // 签名结果
  signedData?: string;                  // 已签名数据
  publicKey?: string;                   // 公钥
  algorithm: string;                    // 签名算法
  timestamp: Date;                      // 签名时间
  requestId: string;                    // 对应请求ID
  processingTime: number;               // 处理时间(ms)
  error?: {
    code: string;
    message: string;
    retryable: boolean;                 // 是否可重试
  };
}

9. ModuleEventBus(模块事件总线)

描述:基于事件驱动的模块间通信机制,支持松耦合集成。

属性

interface ModuleEventBus {
  // 事件订阅
  subscribe<T>(eventType: string, handler: EventHandler<T>): void;
  unsubscribe(eventType: string, handler: EventHandler<any>): void;

  // 事件发布
  publish<T>(event: ModuleEvent<T>): Promise<void>;

  // 同步事件(用于关键操作)
  publishSync<T>(event: ModuleEvent<T>): void;
}

interface ModuleEvent<T = any> {
  type: string;                         // 事件类型
  source: string;                       // 源模块
  target?: string;                      // 目标模块(可选)
  data: T;                              // 事件数据
  timestamp: Date;                      // 事件时间
  correlationId?: string;               // 关联ID
  priority: 'low' | 'normal' | 'high'; // 优先级
}

// 凭证管理相关事件类型
enum CredentialEvents {
  ACCOUNT_REGISTERED = 'credential.account.registered',
  ACCOUNT_REMOVED = 'credential.account.removed',
  ACCOUNT_STATUS_CHANGED = 'credential.account.status_changed',
  SIGN_REQUEST_COMPLETED = 'credential.sign.completed',
  SIGN_REQUEST_FAILED = 'credential.sign.failed',
  CONFIG_RELOADED = 'credential.config.reloaded',
  POOL_STATUS_CHANGED = 'credential.pool.status_changed'
}

// 其他模块监听的事件数据
interface AccountStatusChangedEvent {
  accountId: string;
  platform: Platform;
  oldStatus: AccountHealth;
  newStatus: AccountHealth;
  reason?: string;
  affectedPools: string[];              // 受影响的账户池
}

interface SignRequestCompletedEvent {
  requestId: string;
  accountId: string;
  platform: Platform;
  success: boolean;
  processingTime: number;
  signatureAlgorithm: string;
}

10. CrossModuleServiceInterface(跨模块服务接口)

描述:定义标准化的服务接口,供其他模块直接调用。

属性

interface CrossModuleServiceInterface {
  // 服务注册发现
  registerService(serviceName: string, serviceInstance: any): void;
  getService<T>(serviceName: string): T | null;
  listServices(): string[];

  // 健康检查
  checkServiceHealth(serviceName: string): Promise<ServiceHealthStatus>;

  // 服务依赖管理
  addDependency(serviceName: string, dependsOn: string[]): void;
  resolveDependencies(): Map<string, string[]>;
}

// 对外提供的核心服务
interface CredentialManagementService {
  name: 'credential-manager';
  version: string;

  // 核心功能接口
  signMessage(accountId: string, message: Uint8Array): Promise<string>;
  getAccountCredentials(accountId: string): Promise<Credentials | null>;
  selectAccountForPlatform(platform: Platform, poolId?: string): Promise<string | null>;

  // 管理接口
  reloadConfiguration(): Promise<boolean>;
  getSystemStatus(): Promise<SystemStatus>;

  // 监控接口
  getMetrics(): Promise<PerformanceMetrics>;
  getAccountStatistics(): Promise<AccountStatistics>;
}

interface SystemStatus {
  status: 'healthy' | 'degraded' | 'critical';
  uptime: number;                       // 运行时间(ms)
  totalAccounts: number;                // 总账户数
  activeAccounts: number;               // 活跃账户数
  totalPools: number;                   // 总账户池数
  lastConfigReload: Date;               // 最后配置重载时间
  averageSignTime: number;              // 平均签名时间
  requestsPerMinute: number;            // 每分钟请求数
}

集成示例:与交易模块的典型交互流程

// 1. 交易模块发起交易请求
class TradingModule {
  async executeTrade(tradeRequest: TradeRequest) {
    // 选择合适的账户
    const availableAccounts = await credentialService.getAvailableAccountsForTrading({
      platform: tradeRequest.platform,
      poolId: 'main-trading-pool',
      minHealthScore: 0.9
    });

    if (availableAccounts.length === 0) {
      throw new Error('No healthy accounts available for trading');
    }

    const selectedAccount = availableAccounts[0];

    // 构造签名请求
    const signRequest: TradingSignRequest = {
      accountId: selectedAccount.accountId,
      platform: tradeRequest.platform,
      orderData: tradeRequest.orderData,
      requestId: generateRequestId(),
      timestamp: Date.now(),
      urgency: tradeRequest.urgency || 'normal'
    };

    // 请求签名
    const signResponse = await credentialService.signTradingRequest(signRequest);

    if (!signResponse.success) {
      // 处理签名失败,可能尝试其他账户
      await this.handleSigningFailure(signRequest, signResponse.error);
      return;
    }

    // 执行交易
    const tradeResult = await this.submitToExchange(signResponse);

    // 更新账户状态
    await credentialService.updateAccountAfterTrade(selectedAccount.accountId, tradeResult);
  }
}

// 2. 事件驱动的状态同步
credentialEventBus.subscribe(CredentialEvents.ACCOUNT_STATUS_CHANGED, (event: AccountStatusChangedEvent) => {
  if (event.newStatus === AccountHealth.CRITICAL) {
    // 通知交易模块暂停使用该账户
    tradingModule.pauseAccountUsage(event.accountId);
  }
});

// 3. 监控模块集成
class MonitoringModule {
  async getSystemOverview() {
    const credentialStatus = await credentialService.getSystemStatus();
    const tradingMetrics = await tradingService.getMetrics();

    return {
      credential: credentialStatus,
      trading: tradingMetrics,
      integration: this.checkIntegrationHealth()
    };
  }
}

Phase 1.1 状态:✅ 数据模型设计完成 (更新支持对冲业务 + 模块间交互) 关键更新

  • 添加HedgingAccountPool支持账户池管理
  • 扩展AccountStatus支持实时监控
  • 基于现有AccountRegistry简化模式设计
  • 新增模块间交互接口:TradingModuleIntegration、ModuleEventBus、CrossModuleServiceInterface
  • 提供标准化的交易签名服务接口
  • 支持事件驱动的松耦合模块通信
  • 完整的系统状态监控和服务发现机制
  • 符合宪章v1.6.0架构简化要求
  • 调用链控制在3层以内,避免过度设计

模块集成能力

  • ✅ 交易模块:提供签名服务、账户选择、状态更新
  • ✅ 风控模块:实时账户健康监控、风险状态通知
  • ✅ 监控模块:系统状态查询、性能指标统计
  • ✅ 对冲模块:账户池管理、负载均衡、故障转移

下一步:生成API契约定义