import { Injectable, Logger, Inject, forwardRef } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  JsonRpcProvider,
  Contract,
  parseUnits,
  formatUnits,
  Transaction,
  Signature,
  recoverAddress,
} from 'ethers';
import { ChainConfigService } from './chain-config.service';
import { RpcProviderManager } from './rpc-provider-manager.service';
import { ChainType } from '@/domain/value-objects';
import { ChainTypeEnum } from '@/domain/enums';

// ERC20 ABI for transfer
const ERC20_TRANSFER_ABI = [
  'function transfer(address to, uint256 amount) returns (bool)',
  'function balanceOf(address owner) view returns (uint256)',
  'function decimals() view returns (uint8)',
  'function symbol() view returns (string)',
];

export interface TransferResult {
  success: boolean;
  txHash?: string;
  error?: string;
  gasUsed?: string;
  blockNumber?: number;
}

// 支持的代币类型
export type TokenType = 'DUSDT' | 'EUSDT' | 'FUSDT';

// MPC 签名客户端接口（避免循环依赖）
export interface IMpcSigningClient {
  // C2C Bot 热钱包
  isConfigured(): boolean;
  getHotWalletAddress(): string;
  signMessage(messageHash: string): Promise<string>;
  // eUSDT (积分股) 做市商钱包
  isEusdtMarketMakerConfigured(): boolean;
  getEusdtMarketMakerAddress(): string;
  signMessageAsEusdtMarketMaker(messageHash: string): Promise<string>;
  // fUSDT (积分值) 做市商钱包
  isFusdtMarketMakerConfigured(): boolean;
  getFusdtMarketMakerAddress(): string;
  signMessageAsFusdtMarketMaker(messageHash: string): Promise<string>;
  // 100亿销毁池钱包
  isBurnPoolConfigured(): boolean;
  getBurnPoolAddress(): string;
  signMessageAsBurnPool(messageHash: string): Promise<string>;
  // 200万挖矿池钱包
  isMiningPoolConfigured(): boolean;
  getMiningPoolAddress(): string;
  signMessageAsMiningPool(messageHash: string): Promise<string>;
  // fUSDT 注入钱包（认种自动转积分值到做市商）
  isFusdtInjectionConfigured(): boolean;
  getFusdtInjectionAddress(): string;
  signMessageAsFusdtInjection(messageHash: string): Promise<string>;
}

// 池账户类型（用于 transferTokenAsPoolAccount）
export type PoolWalletType = 'BURN_POOL' | 'MINING_POOL';

export const MPC_SIGNING_CLIENT = Symbol('MPC_SIGNING_CLIENT');

/**
 * ERC20 转账服务
 *
 * 用于从系统热钱包发送 ERC20 代币到用户指定地址
 * 使用 MPC 签名替代私钥签名，提高安全性
 */
@Injectable()
export class Erc20TransferService {
  private readonly logger = new Logger(Erc20TransferService.name);
  // C2C Bot 热钱包地址
  private readonly hotWalletAddress: string;
  // eUSDT (积分股) 做市商钱包地址
  private readonly eusdtMarketMakerAddress: string;
  // fUSDT (积分值) 做市商钱包地址
  private readonly fusdtMarketMakerAddress: string;
  // 100亿销毁池钱包地址
  private readonly burnPoolAddress: string;
  // 200万挖矿池钱包地址
  private readonly miningPoolAddress: string;
  // fUSDT 注入钱包地址（认种自动转积分值到做市商）
  private readonly fusdtInjectionAddress: string;
  private mpcSigningClient: IMpcSigningClient | null = null;

  constructor(
    private readonly configService: ConfigService,
    private readonly chainConfig: ChainConfigService,
    private readonly rpcProviderManager: RpcProviderManager,
  ) {
    this.hotWalletAddress = this.configService.get<string>('C2C_BOT_WALLET_ADDRESS', '');
    this.eusdtMarketMakerAddress = this.configService.get<string>('EUSDT_MARKET_MAKER_ADDRESS', '');
    this.fusdtMarketMakerAddress = this.configService.get<string>('FUSDT_MARKET_MAKER_ADDRESS', '');
    this.burnPoolAddress = this.configService.get<string>('BURN_POOL_WALLET_ADDRESS', '');
    this.miningPoolAddress = this.configService.get<string>('MINING_POOL_WALLET_ADDRESS', '');
    this.fusdtInjectionAddress = this.configService.get<string>('FUSDT_INJECTION_WALLET_ADDRESS', '');
    this.initializeWalletConfig();
  }

  /**
   * 设置 MPC 签名客户端（用于延迟注入，避免循环依赖）
   */
  setMpcSigningClient(client: IMpcSigningClient): void {
    this.mpcSigningClient = client;
    this.logger.log(`[INIT] MPC Signing Client injected`);
  }

  /**
   * 获取某条链当前活跃的 provider（由 RpcProviderManager 统一管理，支持故障转移）
   */
  private getProvider(chainType: ChainTypeEnum): JsonRpcProvider {
    return this.rpcProviderManager.getProvider(chainType);
  }

  /**
   * 判断错误是否为 RPC 连接类错误（需要触发故障转移）
   * 区分 RPC 网络错误（503、超时等）和合约执行错误（revert、余额不足等）
   */
  private isRpcConnectionError(error: any): boolean {
    const message = (error?.message || '').toLowerCase();
    return (
      message.includes('could not detect network') ||
      message.includes('connection refused') ||
      message.includes('timeout') ||
      message.includes('econnrefused') ||
      message.includes('enotfound') ||
      message.includes('503') ||
      message.includes('502') ||
      message.includes('server error') ||
      message.includes('missing response') ||
      message.includes('request failed') ||
      error?.code === 'NETWORK_ERROR' ||
      error?.code === 'SERVER_ERROR' ||
      error?.code === 'TIMEOUT'
    );
  }

  /**
   * 初始化钱包配置检查（provider 由 RpcProviderManager 统一管理）
   */
  private initializeWalletConfig(): void {
    // 检查热钱包地址配置
    if (this.hotWalletAddress) {
      this.logger.log(`[INIT] C2C Bot wallet address configured: ${this.hotWalletAddress}`);
    } else {
      this.logger.warn('[INIT] C2C_BOT_WALLET_ADDRESS not configured, C2C transfers will fail');
    }

    // 检查 eUSDT 做市商钱包地址配置
    if (this.eusdtMarketMakerAddress) {
      this.logger.log(`[INIT] eUSDT Market Maker address configured: ${this.eusdtMarketMakerAddress}`);
    } else {
      this.logger.warn('[INIT] EUSDT_MARKET_MAKER_ADDRESS not configured');
    }

    // 检查 fUSDT 做市商钱包地址配置
    if (this.fusdtMarketMakerAddress) {
      this.logger.log(`[INIT] fUSDT Market Maker address configured: ${this.fusdtMarketMakerAddress}`);
    } else {
      this.logger.warn('[INIT] FUSDT_MARKET_MAKER_ADDRESS not configured');
    }

    // 检查 fUSDT 注入钱包地址配置
    if (this.fusdtInjectionAddress) {
      this.logger.log(`[INIT] fUSDT Injection wallet configured: ${this.fusdtInjectionAddress}`);
    } else {
      this.logger.warn('[INIT] FUSDT_INJECTION_WALLET_ADDRESS not configured (adoption auto-injection disabled)');
    }
  }

  /**
   * 获取 C2C Bot 热钱包地址
   */
  getHotWalletAddress(chainType: ChainTypeEnum): string | null {
    // MPC 钱包地址在所有 EVM 链上相同
    return this.hotWalletAddress || null;
  }

  /**
   * 获取 eUSDT 做市商钱包地址
   */
  getEusdtMarketMakerAddress(chainType: ChainTypeEnum): string | null {
    return this.eusdtMarketMakerAddress || null;
  }

  /**
   * 获取 fUSDT 做市商钱包地址
   */
  getFusdtMarketMakerAddress(chainType: ChainTypeEnum): string | null {
    return this.fusdtMarketMakerAddress || null;
  }

  /**
   * 获取热钱包 USDT 余额
   */
  async getHotWalletBalance(chainType: ChainTypeEnum): Promise<string> {
    const provider = this.getProvider(chainType);

    if (!this.hotWalletAddress) {
      throw new Error('Hot wallet address not configured');
    }

    const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
    const contract = new Contract(config.usdtContract, ERC20_TRANSFER_ABI, provider);

    const balance = await contract.balanceOf(this.hotWalletAddress);
    const decimals = await contract.decimals();

    return formatUnits(balance, decimals);
  }

  /**
   * 执行 ERC20 转账（使用 MPC 签名）
   *
   * @param chainType 链类型 (KAVA, BSC)
   * @param toAddress 接收地址
   * @param amount 转账金额 (人类可读格式，如 "100.5")
   * @returns 转账结果
   */
  async transferUsdt(
    chainType: ChainTypeEnum,
    toAddress: string,
    amount: string,
  ): Promise<TransferResult> {
    this.logger.log(`[TRANSFER] Starting USDT transfer with MPC signing`);
    this.logger.log(`[TRANSFER] Chain: ${chainType}`);
    this.logger.log(`[TRANSFER] To: ${toAddress}`);
    this.logger.log(`[TRANSFER] Amount: ${amount} USDT`);

    const provider = this.getProvider(chainType);

    if (!this.mpcSigningClient || !this.mpcSigningClient.isConfigured()) {
      const error = 'MPC signing client not configured';
      this.logger.error(`[TRANSFER] ${error}`);
      return { success: false, error };
    }

    if (!this.hotWalletAddress) {
      const error = 'Hot wallet address not configured';
      this.logger.error(`[TRANSFER] ${error}`);
      return { success: false, error };
    }

    try {
      const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
      const contract = new Contract(config.usdtContract, ERC20_TRANSFER_ABI, provider);

      // 获取代币精度
      const decimals = await contract.decimals();
      this.logger.log(`[TRANSFER] Token decimals: ${decimals}`);

      // 转换金额
      const amountInWei = parseUnits(amount, decimals);
      this.logger.log(`[TRANSFER] Amount in wei: ${amountInWei.toString()}`);

      // 检查余额
      const balance = await contract.balanceOf(this.hotWalletAddress);
      this.logger.log(`[TRANSFER] Hot wallet balance: ${formatUnits(balance, decimals)} USDT`);

      if (balance < amountInWei) {
        const error = 'Insufficient USDT balance in hot wallet';
        this.logger.error(`[TRANSFER] ${error}`);
        return { success: false, error };
      }

      // 构建交易
      this.logger.log(`[TRANSFER] Building transaction...`);
      const nonce = await provider.getTransactionCount(this.hotWalletAddress);
      const feeData = await provider.getFeeData();

      // ERC20 transfer 的 calldata
      const transferData = contract.interface.encodeFunctionData('transfer', [toAddress, amountInWei]);

      // 估算 gas
      const gasEstimate = await provider.estimateGas({
        from: this.hotWalletAddress,
        to: config.usdtContract,
        data: transferData,
      });

      const gasLimit = gasEstimate * BigInt(120) / BigInt(100); // 增加 20% buffer

      // 检测链是否支持 EIP-1559
      // 如果 maxFeePerGas 为 null 或 0，则使用 legacy 交易
      const supportsEip1559 = feeData.maxFeePerGas && feeData.maxFeePerGas > BigInt(0);
      this.logger.log(`[TRANSFER] Chain supports EIP-1559: ${supportsEip1559}`);
      this.logger.log(`[TRANSFER] Fee data: gasPrice=${feeData.gasPrice}, maxFeePerGas=${feeData.maxFeePerGas}`);

      let tx: Transaction;
      if (supportsEip1559) {
        // EIP-1559 交易 (type 2)
        tx = Transaction.from({
          type: 2,
          chainId: config.chainId,
          nonce,
          to: config.usdtContract,
          data: transferData,
          gasLimit,
          maxFeePerGas: feeData.maxFeePerGas,
          maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        });
        this.logger.log(`[TRANSFER] Built EIP-1559 transaction`);
      } else {
        // Legacy 交易 (type 0)
        const gasPrice = feeData.gasPrice || BigInt(1000000000); // 默认 1 gwei
        tx = Transaction.from({
          type: 0,
          chainId: config.chainId,
          nonce,
          to: config.usdtContract,
          data: transferData,
          gasLimit,
          gasPrice,
        });
        this.logger.log(`[TRANSFER] Built legacy transaction with gasPrice=${gasPrice}`);
      }

      this.logger.log(`[TRANSFER] Transaction built: nonce=${nonce}, gasLimit=${tx.gasLimit}`);

      // 获取交易哈希用于签名
      const unsignedTxHash = tx.unsignedHash;
      this.logger.log(`[TRANSFER] Unsigned tx hash: ${unsignedTxHash}`);

      // 使用 MPC 签名
      this.logger.log(`[TRANSFER] Requesting MPC signature...`);
      const signatureHex = await this.mpcSigningClient.signMessage(unsignedTxHash);
      this.logger.log(`[TRANSFER] MPC signature obtained: ${signatureHex.slice(0, 20)}...`);

      // 解析签名 - MPC 返回 64 字节 (r+s)，需要转换为 ethers.js 格式
      // 确保有 0x 前缀
      const normalizedSig = signatureHex.startsWith('0x') ? signatureHex : `0x${signatureHex}`;
      this.logger.log(`[TRANSFER] Normalized signature: ${normalizedSig.slice(0, 22)}...`);

      // MPC 签名是 64 字节 (r: 32 bytes + s: 32 bytes)，需要添加 v (recovery id)
      // 对于 EIP-1559 交易，v = 0 或 1 (yParity)
      // 我们需要尝试两个值来恢复正确的地址
      const sigBytes = normalizedSig.slice(2); // 去掉 0x
      const r = `0x${sigBytes.slice(0, 64)}`;
      const s = `0x${sigBytes.slice(64, 128)}`;

      this.logger.log(`[TRANSFER] Signature r: ${r.slice(0, 20)}...`);
      this.logger.log(`[TRANSFER] Signature s: ${s.slice(0, 20)}...`);

      // 尝试 yParity 0 和 1 来找到正确的 recovery id
      let signature: Signature | null = null;
      for (const yParity of [0, 1] as const) {
        try {
          const testSig = Signature.from({ r, s, yParity });
          // 使用 recoverAddress 验证签名
          const recoveredAddress = recoverAddress(unsignedTxHash, testSig);
          this.logger.log(`[TRANSFER] Recovered address with yParity=${yParity}: ${recoveredAddress}`);

          if (recoveredAddress.toLowerCase() === this.hotWalletAddress.toLowerCase()) {
            this.logger.log(`[TRANSFER] Found correct yParity: ${yParity}`);
            signature = testSig;
            break;
          }
        } catch (e) {
          this.logger.debug(`[TRANSFER] yParity=${yParity} failed: ${e}`);
        }
      }

      if (!signature) {
        throw new Error('Failed to recover correct signature - address mismatch');
      }

      // 创建已签名交易
      const signedTx = tx.clone();
      signedTx.signature = signature;

      // 广播交易
      this.logger.log(`[TRANSFER] Broadcasting transaction...`);
      const txResponse = await provider.broadcastTransaction(signedTx.serialized);
      this.logger.log(`[TRANSFER] Transaction sent: ${txResponse.hash}`);

      // 等待确认
      this.logger.log(`[TRANSFER] Waiting for confirmation...`);
      const receipt = await txResponse.wait();

      if (receipt && receipt.status === 1) {
        this.logger.log(`[TRANSFER] Transaction confirmed!`);
        this.logger.log(`[TRANSFER] Block: ${receipt.blockNumber}`);
        this.logger.log(`[TRANSFER] Gas used: ${receipt.gasUsed.toString()}`);

        this.rpcProviderManager.reportSuccess(chainType);
        return {
          success: true,
          txHash: txResponse.hash,
          gasUsed: receipt.gasUsed.toString(),
          blockNumber: receipt.blockNumber,
        };
      } else {
        const error = 'Transaction failed (reverted)';
        this.logger.error(`[TRANSFER] ${error}`);
        return { success: false, txHash: txResponse.hash, error };
      }
    } catch (error: any) {
      if (this.isRpcConnectionError(error)) {
        this.rpcProviderManager.reportFailure(chainType, error);
      }
      this.logger.error(`[TRANSFER] Transfer failed:`, error);
      return {
        success: false,
        error: error.message || 'Unknown error during transfer',
      };
    }
  }

  /**
   * 获取指定代币的合约地址
   */
  private getTokenContract(chainType: ChainTypeEnum, tokenType: TokenType): string {
    const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
    switch (tokenType) {
      case 'DUSDT':
        return config.usdtContract;
      case 'EUSDT':
        return config.eUsdtContract;
      case 'FUSDT':
        return config.fUsdtContract;
      default:
        throw new Error(`Unsupported token type: ${tokenType}`);
    }
  }

  /**
   * 获取热钱包指定代币余额
   */
  async getTokenBalance(chainType: ChainTypeEnum, tokenType: TokenType): Promise<string> {
    const provider = this.getProvider(chainType);

    if (!this.hotWalletAddress) {
      throw new Error('Hot wallet address not configured');
    }

    const contractAddress = this.getTokenContract(chainType, tokenType);
    if (!contractAddress) {
      throw new Error(`Token ${tokenType} not configured for chain ${chainType}`);
    }

    const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);
    const balance = await contract.balanceOf(this.hotWalletAddress);
    const decimals = await contract.decimals();

    return formatUnits(balance, decimals);
  }

  /**
   * 通用 ERC20 代币转账（使用 MPC 签名）
   *
   * @param chainType 链类型 (KAVA, BSC)
   * @param tokenType 代币类型 (DUSDT, EUSDT, FUSDT)
   * @param toAddress 接收地址
   * @param amount 转账金额 (人类可读格式，如 "100.5")
   * @returns 转账结果
   */
  async transferToken(
    chainType: ChainTypeEnum,
    tokenType: TokenType,
    toAddress: string,
    amount: string,
  ): Promise<TransferResult> {
    const tokenName = tokenType === 'EUSDT' ? '积分股' : tokenType === 'FUSDT' ? '积分值' : 'dUSDT';
    this.logger.log(`[TRANSFER] Starting ${tokenType} (${tokenName}) transfer with MPC signing`);
    this.logger.log(`[TRANSFER] Chain: ${chainType}`);
    this.logger.log(`[TRANSFER] To: ${toAddress}`);
    this.logger.log(`[TRANSFER] Amount: ${amount} ${tokenType}`);

    const provider = this.getProvider(chainType);

    if (!this.mpcSigningClient || !this.mpcSigningClient.isConfigured()) {
      const error = 'MPC signing client not configured';
      this.logger.error(`[TRANSFER] ${error}`);
      return { success: false, error };
    }

    if (!this.hotWalletAddress) {
      const error = 'Hot wallet address not configured';
      this.logger.error(`[TRANSFER] ${error}`);
      return { success: false, error };
    }

    try {
      const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
      const contractAddress = this.getTokenContract(chainType, tokenType);

      if (!contractAddress) {
        const error = `Token ${tokenType} not configured for chain ${chainType}`;
        this.logger.error(`[TRANSFER] ${error}`);
        return { success: false, error };
      }

      const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);

      // 获取代币精度
      const decimals = await contract.decimals();
      this.logger.log(`[TRANSFER] Token decimals: ${decimals}`);

      // 转换金额
      const amountInWei = parseUnits(amount, decimals);
      this.logger.log(`[TRANSFER] Amount in wei: ${amountInWei.toString()}`);

      // 检查余额
      const balance = await contract.balanceOf(this.hotWalletAddress);
      this.logger.log(`[TRANSFER] Hot wallet balance: ${formatUnits(balance, decimals)} ${tokenType}`);

      if (balance < amountInWei) {
        const error = `Insufficient ${tokenType} balance in hot wallet`;
        this.logger.error(`[TRANSFER] ${error}`);
        return { success: false, error };
      }

      // 构建交易
      this.logger.log(`[TRANSFER] Building transaction...`);
      const nonce = await provider.getTransactionCount(this.hotWalletAddress);
      const feeData = await provider.getFeeData();

      // ERC20 transfer 的 calldata
      const transferData = contract.interface.encodeFunctionData('transfer', [toAddress, amountInWei]);

      // 估算 gas
      const gasEstimate = await provider.estimateGas({
        from: this.hotWalletAddress,
        to: contractAddress,
        data: transferData,
      });

      const gasLimit = gasEstimate * BigInt(120) / BigInt(100); // 增加 20% buffer

      // 检测链是否支持 EIP-1559
      const supportsEip1559 = feeData.maxFeePerGas && feeData.maxFeePerGas > BigInt(0);

      let tx: Transaction;
      if (supportsEip1559) {
        tx = Transaction.from({
          type: 2,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          maxFeePerGas: feeData.maxFeePerGas,
          maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        });
      } else {
        const gasPrice = feeData.gasPrice || BigInt(1000000000);
        tx = Transaction.from({
          type: 0,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          gasPrice,
        });
      }

      this.logger.log(`[TRANSFER] Transaction built: nonce=${nonce}, gasLimit=${tx.gasLimit}`);

      // 获取交易哈希用于签名
      const unsignedTxHash = tx.unsignedHash;
      this.logger.log(`[TRANSFER] Unsigned tx hash: ${unsignedTxHash}`);

      // 使用 MPC 签名
      this.logger.log(`[TRANSFER] Requesting MPC signature...`);
      const signatureHex = await this.mpcSigningClient.signMessage(unsignedTxHash);
      this.logger.log(`[TRANSFER] MPC signature obtained: ${signatureHex.slice(0, 20)}...`);

      // 解析签名
      const normalizedSig = signatureHex.startsWith('0x') ? signatureHex : `0x${signatureHex}`;
      const sigBytes = normalizedSig.slice(2);
      const r = `0x${sigBytes.slice(0, 64)}`;
      const s = `0x${sigBytes.slice(64, 128)}`;

      // 尝试 yParity 0 和 1 来找到正确的 recovery id
      let signature: Signature | null = null;
      for (const yParity of [0, 1] as const) {
        try {
          const testSig = Signature.from({ r, s, yParity });
          const recoveredAddress = recoverAddress(unsignedTxHash, testSig);

          if (recoveredAddress.toLowerCase() === this.hotWalletAddress.toLowerCase()) {
            this.logger.log(`[TRANSFER] Found correct yParity: ${yParity}`);
            signature = testSig;
            break;
          }
        } catch (e) {
          this.logger.debug(`[TRANSFER] yParity=${yParity} failed: ${e}`);
        }
      }

      if (!signature) {
        throw new Error('Failed to recover correct signature - address mismatch');
      }

      // 创建已签名交易
      const signedTx = tx.clone();
      signedTx.signature = signature;

      // 广播交易
      this.logger.log(`[TRANSFER] Broadcasting transaction...`);
      const txResponse = await provider.broadcastTransaction(signedTx.serialized);
      this.logger.log(`[TRANSFER] Transaction sent: ${txResponse.hash}`);

      // 等待确认
      this.logger.log(`[TRANSFER] Waiting for confirmation...`);
      const receipt = await txResponse.wait();

      if (receipt && receipt.status === 1) {
        this.logger.log(`[TRANSFER] Transaction confirmed!`);
        this.logger.log(`[TRANSFER] Block: ${receipt.blockNumber}`);
        this.logger.log(`[TRANSFER] Gas used: ${receipt.gasUsed.toString()}`);

        this.rpcProviderManager.reportSuccess(chainType);
        return {
          success: true,
          txHash: txResponse.hash,
          gasUsed: receipt.gasUsed.toString(),
          blockNumber: receipt.blockNumber,
        };
      } else {
        const error = 'Transaction failed (reverted)';
        this.logger.error(`[TRANSFER] ${error}`);
        return { success: false, txHash: txResponse.hash, error };
      }
    } catch (error: any) {
      if (this.isRpcConnectionError(error)) {
        this.rpcProviderManager.reportFailure(chainType, error);
      }
      this.logger.error(`[TRANSFER] Transfer failed:`, error);
      return {
        success: false,
        error: error.message || 'Unknown error during transfer',
      };
    }
  }

  /**
   * 检查 C2C Bot 热钱包是否已配置
   */
  isConfigured(chainType: ChainTypeEnum): boolean {
    try {
      this.rpcProviderManager.getProvider(chainType);
      return !!this.hotWalletAddress && !!this.mpcSigningClient?.isConfigured();
    } catch {
      return false;
    }
  }

  /**
   * 检查 eUSDT 做市商钱包是否已配置
   */
  isEusdtMarketMakerConfigured(chainType: ChainTypeEnum): boolean {
    try {
      this.rpcProviderManager.getProvider(chainType);
      return !!this.eusdtMarketMakerAddress && !!this.mpcSigningClient?.isEusdtMarketMakerConfigured();
    } catch {
      return false;
    }
  }

  /**
   * 检查 fUSDT 做市商钱包是否已配置
   */
  isFusdtMarketMakerConfigured(chainType: ChainTypeEnum): boolean {
    try {
      this.rpcProviderManager.getProvider(chainType);
      return !!this.fusdtMarketMakerAddress && !!this.mpcSigningClient?.isFusdtMarketMakerConfigured();
    } catch {
      return false;
    }
  }

  /**
   * 做市商代币转账（使用做市商 MPC 钱包签名）
   *
   * @param chainType 链类型 (KAVA, BSC)
   * @param tokenType 代币类型 (DUSDT, EUSDT, FUSDT)
   * @param toAddress 接收地址
   * @param amount 转账金额 (人类可读格式，如 "100.5")
   * @returns 转账结果
   */
  async transferTokenAsMarketMaker(
    chainType: ChainTypeEnum,
    tokenType: TokenType,
    toAddress: string,
    amount: string,
  ): Promise<TransferResult> {
    // 根据代币类型选择对应的做市商钱包
    const isEusdt = tokenType === 'EUSDT';
    const marketMakerAddress = isEusdt ? this.eusdtMarketMakerAddress : this.fusdtMarketMakerAddress;
    const tokenName = isEusdt ? '积分股' : '积分值';

    this.logger.log(`[MM-TRANSFER] Starting ${tokenType} (${tokenName}) Market Maker transfer`);
    this.logger.log(`[MM-TRANSFER] Chain: ${chainType}`);
    this.logger.log(`[MM-TRANSFER] From: ${marketMakerAddress}`);
    this.logger.log(`[MM-TRANSFER] To: ${toAddress}`);
    this.logger.log(`[MM-TRANSFER] Amount: ${amount} ${tokenType}`);

    const provider = this.getProvider(chainType);

    // 检查对应钱包是否配置
    if (isEusdt) {
      if (!this.mpcSigningClient || !this.mpcSigningClient.isEusdtMarketMakerConfigured()) {
        const error = 'eUSDT Market Maker MPC signing not configured';
        this.logger.error(`[MM-TRANSFER] ${error}`);
        return { success: false, error };
      }
    } else {
      if (!this.mpcSigningClient || !this.mpcSigningClient.isFusdtMarketMakerConfigured()) {
        const error = 'fUSDT Market Maker MPC signing not configured';
        this.logger.error(`[MM-TRANSFER] ${error}`);
        return { success: false, error };
      }
    }

    if (!marketMakerAddress) {
      const error = `${tokenType} Market Maker wallet address not configured`;
      this.logger.error(`[MM-TRANSFER] ${error}`);
      return { success: false, error };
    }

    try {
      const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
      const contractAddress = this.getTokenContract(chainType, tokenType);

      if (!contractAddress) {
        const error = `Token ${tokenType} not configured for chain ${chainType}`;
        this.logger.error(`[MM-TRANSFER] ${error}`);
        return { success: false, error };
      }

      const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);

      // 获取代币精度
      const decimals = await contract.decimals();
      this.logger.log(`[MM-TRANSFER] Token decimals: ${decimals}`);

      // 转换金额
      const amountInWei = parseUnits(amount, decimals);
      this.logger.log(`[MM-TRANSFER] Amount in wei: ${amountInWei.toString()}`);

      // 检查余额
      const balance = await contract.balanceOf(marketMakerAddress);
      this.logger.log(`[MM-TRANSFER] Market Maker balance: ${formatUnits(balance, decimals)} ${tokenType}`);

      if (balance < amountInWei) {
        const error = `Insufficient ${tokenType} balance in Market Maker wallet`;
        this.logger.error(`[MM-TRANSFER] ${error}`);
        return { success: false, error };
      }

      // 构建交易
      this.logger.log(`[MM-TRANSFER] Building transaction...`);
      const nonce = await provider.getTransactionCount(marketMakerAddress);
      const feeData = await provider.getFeeData();

      // ERC20 transfer 的 calldata
      const transferData = contract.interface.encodeFunctionData('transfer', [toAddress, amountInWei]);

      // 估算 gas
      const gasEstimate = await provider.estimateGas({
        from: marketMakerAddress,
        to: contractAddress,
        data: transferData,
      });

      const gasLimit = gasEstimate * BigInt(120) / BigInt(100); // 增加 20% buffer

      // 检测链是否支持 EIP-1559
      const supportsEip1559 = feeData.maxFeePerGas && feeData.maxFeePerGas > BigInt(0);

      let tx: Transaction;
      if (supportsEip1559) {
        tx = Transaction.from({
          type: 2,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          maxFeePerGas: feeData.maxFeePerGas,
          maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        });
      } else {
        const gasPrice = feeData.gasPrice || BigInt(1000000000);
        tx = Transaction.from({
          type: 0,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          gasPrice,
        });
      }

      this.logger.log(`[MM-TRANSFER] Transaction built: nonce=${nonce}, gasLimit=${tx.gasLimit}`);

      // 获取交易哈希用于签名
      const unsignedTxHash = tx.unsignedHash;
      this.logger.log(`[MM-TRANSFER] Unsigned tx hash: ${unsignedTxHash}`);

      // 使用对应的做市商 MPC 钱包签名
      this.logger.log(`[MM-TRANSFER] Requesting ${tokenType} Market Maker MPC signature...`);
      const signatureHex = isEusdt
        ? await this.mpcSigningClient!.signMessageAsEusdtMarketMaker(unsignedTxHash)
        : await this.mpcSigningClient!.signMessageAsFusdtMarketMaker(unsignedTxHash);
      this.logger.log(`[MM-TRANSFER] MPC signature obtained: ${signatureHex.slice(0, 20)}...`);

      // 解析签名
      const normalizedSig = signatureHex.startsWith('0x') ? signatureHex : `0x${signatureHex}`;
      const sigBytes = normalizedSig.slice(2);
      const r = `0x${sigBytes.slice(0, 64)}`;
      const s = `0x${sigBytes.slice(64, 128)}`;

      // 尝试 yParity 0 和 1 来找到正确的 recovery id
      let signature: Signature | null = null;
      for (const yParity of [0, 1] as const) {
        try {
          const testSig = Signature.from({ r, s, yParity });
          const recoveredAddress = recoverAddress(unsignedTxHash, testSig);

          if (recoveredAddress.toLowerCase() === marketMakerAddress.toLowerCase()) {
            this.logger.log(`[MM-TRANSFER] Found correct yParity: ${yParity}`);
            signature = testSig;
            break;
          }
        } catch (e) {
          this.logger.debug(`[MM-TRANSFER] yParity=${yParity} failed: ${e}`);
        }
      }

      if (!signature) {
        throw new Error('Failed to recover correct signature - address mismatch');
      }

      // 创建已签名交易
      const signedTx = tx.clone();
      signedTx.signature = signature;

      // 广播交易
      this.logger.log(`[MM-TRANSFER] Broadcasting transaction...`);
      const txResponse = await provider.broadcastTransaction(signedTx.serialized);
      this.logger.log(`[MM-TRANSFER] Transaction sent: ${txResponse.hash}`);

      // 等待确认
      this.logger.log(`[MM-TRANSFER] Waiting for confirmation...`);
      const receipt = await txResponse.wait();

      if (receipt && receipt.status === 1) {
        this.logger.log(`[MM-TRANSFER] Transaction confirmed!`);
        this.logger.log(`[MM-TRANSFER] Block: ${receipt.blockNumber}`);
        this.logger.log(`[MM-TRANSFER] Gas used: ${receipt.gasUsed.toString()}`);

        this.rpcProviderManager.reportSuccess(chainType);
        return {
          success: true,
          txHash: txResponse.hash,
          gasUsed: receipt.gasUsed.toString(),
          blockNumber: receipt.blockNumber,
        };
      } else {
        const error = 'Transaction failed (reverted)';
        this.logger.error(`[MM-TRANSFER] ${error}`);
        return { success: false, txHash: txResponse.hash, error };
      }
    } catch (error: any) {
      if (this.isRpcConnectionError(error)) {
        this.rpcProviderManager.reportFailure(chainType, error);
      }
      this.logger.error(`[MM-TRANSFER] Transfer failed:`, error);
      return {
        success: false,
        error: error.message || 'Unknown error during transfer',
      };
    }
  }

  /**
   * 获取 eUSDT 做市商代币余额
   */
  async getEusdtMarketMakerTokenBalance(chainType: ChainTypeEnum): Promise<string> {
    const provider = this.getProvider(chainType);

    if (!this.eusdtMarketMakerAddress) {
      throw new Error('eUSDT Market Maker wallet address not configured');
    }

    const contractAddress = this.getTokenContract(chainType, 'EUSDT');
    if (!contractAddress) {
      throw new Error(`eUSDT not configured for chain ${chainType}`);
    }

    const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);
    const balance = await contract.balanceOf(this.eusdtMarketMakerAddress);
    const decimals = await contract.decimals();

    return formatUnits(balance, decimals);
  }

  /**
   * 获取 fUSDT 做市商代币余额
   */
  async getFusdtMarketMakerTokenBalance(chainType: ChainTypeEnum): Promise<string> {
    const provider = this.getProvider(chainType);

    if (!this.fusdtMarketMakerAddress) {
      throw new Error('fUSDT Market Maker wallet address not configured');
    }

    const contractAddress = this.getTokenContract(chainType, 'FUSDT');
    if (!contractAddress) {
      throw new Error(`fUSDT not configured for chain ${chainType}`);
    }

    const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);
    const balance = await contract.balanceOf(this.fusdtMarketMakerAddress);
    const decimals = await contract.decimals();

    return formatUnits(balance, decimals);
  }

  // ============ fUSDT 注入钱包方法（认种自动转积分值到做市商） ============

  /**
   * 检查 fUSDT 注入钱包是否已配置
   */
  isFusdtInjectionConfigured(chainType: ChainTypeEnum): boolean {
    try {
      this.rpcProviderManager.getProvider(chainType);
      return !!this.fusdtInjectionAddress && !!this.mpcSigningClient?.isFusdtInjectionConfigured();
    } catch {
      return false;
    }
  }

  /**
   * 获取 fUSDT 注入钱包地址
   */
  getFusdtInjectionAddress(): string | null {
    return this.fusdtInjectionAddress || null;
  }

  /**
   * 获取 fUSDT 注入钱包的 fUSDT 链上余额
   */
  async getFusdtInjectionTokenBalance(chainType: ChainTypeEnum): Promise<string> {
    const provider = this.getProvider(chainType);

    if (!this.fusdtInjectionAddress) {
      throw new Error('fUSDT Injection wallet address not configured');
    }

    const contractAddress = this.getTokenContract(chainType, 'FUSDT');
    if (!contractAddress) {
      throw new Error(`fUSDT not configured for chain ${chainType}`);
    }

    const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);
    const balance = await contract.balanceOf(this.fusdtInjectionAddress);
    const decimals = await contract.decimals();

    return formatUnits(balance, decimals);
  }

  /**
   * fUSDT 注入钱包转账到做市商钱包（认种触发）
   *
   * @param chainType 链类型
   * @param toAddress 做市商钱包地址
   * @param amount 转账金额 (人类可读格式)
   * @param memo 分类账备注（含认种信息）
   * @returns 转账结果
   */
  async transferFusdtAsInjectionWallet(
    chainType: ChainTypeEnum,
    toAddress: string,
    amount: string,
    memo?: string,
  ): Promise<TransferResult> {
    this.logger.log(`[INJECTION-TRANSFER] Starting fUSDT injection transfer`);
    this.logger.log(`[INJECTION-TRANSFER] From: ${this.fusdtInjectionAddress}`);
    this.logger.log(`[INJECTION-TRANSFER] To: ${toAddress}`);
    this.logger.log(`[INJECTION-TRANSFER] Amount: ${amount} fUSDT`);
    if (memo) {
      this.logger.log(`[INJECTION-TRANSFER] Memo: ${memo}`);
    }

    const provider = this.getProvider(chainType);

    if (!this.mpcSigningClient || !this.mpcSigningClient.isFusdtInjectionConfigured()) {
      const error = 'fUSDT Injection MPC signing not configured';
      this.logger.error(`[INJECTION-TRANSFER] ${error}`);
      return { success: false, error };
    }

    if (!this.fusdtInjectionAddress) {
      const error = 'fUSDT Injection wallet address not configured';
      this.logger.error(`[INJECTION-TRANSFER] ${error}`);
      return { success: false, error };
    }

    try {
      const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
      const contractAddress = this.getTokenContract(chainType, 'FUSDT');

      if (!contractAddress) {
        const error = `fUSDT not configured for chain ${chainType}`;
        this.logger.error(`[INJECTION-TRANSFER] ${error}`);
        return { success: false, error };
      }

      const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);

      const decimals = await contract.decimals();
      const amountInWei = parseUnits(amount, decimals);

      // 检查余额
      const balance = await contract.balanceOf(this.fusdtInjectionAddress);
      this.logger.log(`[INJECTION-TRANSFER] Injection wallet balance: ${formatUnits(balance, decimals)} fUSDT`);

      if (balance < amountInWei) {
        const error = `Insufficient fUSDT balance in injection wallet (need ${amount}, have ${formatUnits(balance, decimals)})`;
        this.logger.error(`[INJECTION-TRANSFER] ${error}`);
        return { success: false, error };
      }

      // 构建交易
      const nonce = await provider.getTransactionCount(this.fusdtInjectionAddress);
      const feeData = await provider.getFeeData();
      const transferData = contract.interface.encodeFunctionData('transfer', [toAddress, amountInWei]);

      const gasEstimate = await provider.estimateGas({
        from: this.fusdtInjectionAddress,
        to: contractAddress,
        data: transferData,
      });
      const gasLimit = gasEstimate * BigInt(120) / BigInt(100);

      const supportsEip1559 = feeData.maxFeePerGas && feeData.maxFeePerGas > BigInt(0);

      let tx: Transaction;
      if (supportsEip1559) {
        tx = Transaction.from({
          type: 2,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          maxFeePerGas: feeData.maxFeePerGas,
          maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        });
      } else {
        const gasPrice = feeData.gasPrice || BigInt(1000000000);
        tx = Transaction.from({
          type: 0,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          gasPrice,
        });
      }

      const unsignedTxHash = tx.unsignedHash;

      // 使用注入钱包 MPC 签名
      this.logger.log(`[INJECTION-TRANSFER] Requesting fUSDT Injection MPC signature...`);
      const signatureHex = await this.mpcSigningClient!.signMessageAsFusdtInjection(unsignedTxHash);

      // 解析签名
      const normalizedSig = signatureHex.startsWith('0x') ? signatureHex : `0x${signatureHex}`;
      const sigBytes = normalizedSig.slice(2);
      const r = `0x${sigBytes.slice(0, 64)}`;
      const s = `0x${sigBytes.slice(64, 128)}`;

      let signature: Signature | null = null;
      for (const yParity of [0, 1] as const) {
        try {
          const testSig = Signature.from({ r, s, yParity });
          const recoveredAddress = recoverAddress(unsignedTxHash, testSig);
          if (recoveredAddress.toLowerCase() === this.fusdtInjectionAddress.toLowerCase()) {
            signature = testSig;
            break;
          }
        } catch (e) {
          this.logger.debug(`[INJECTION-TRANSFER] yParity=${yParity} failed: ${e}`);
        }
      }

      if (!signature) {
        throw new Error('Failed to recover correct signature - address mismatch');
      }

      const signedTx = tx.clone();
      signedTx.signature = signature;

      this.logger.log(`[INJECTION-TRANSFER] Broadcasting transaction...`);
      const txResponse = await provider.broadcastTransaction(signedTx.serialized);
      this.logger.log(`[INJECTION-TRANSFER] Transaction sent: ${txResponse.hash}`);

      const receipt = await txResponse.wait();

      if (receipt && receipt.status === 1) {
        this.logger.log(`[INJECTION-TRANSFER] Transaction confirmed! Block: ${receipt.blockNumber}`);
        this.rpcProviderManager.reportSuccess(chainType);
        return {
          success: true,
          txHash: txResponse.hash,
          gasUsed: receipt.gasUsed.toString(),
          blockNumber: receipt.blockNumber,
        };
      } else {
        return { success: false, txHash: txResponse.hash, error: 'Transaction failed (reverted)' };
      }
    } catch (error: any) {
      if (this.isRpcConnectionError(error)) {
        this.rpcProviderManager.reportFailure(chainType, error);
      }
      this.logger.error(`[INJECTION-TRANSFER] Transfer failed:`, error);
      return {
        success: false,
        error: error.message || 'Unknown error during transfer',
      };
    }
  }

  // ============ 池账户钱包方法 ============

  /**
   * 获取池钱包地址
   */
  getPoolWalletAddress(poolType: PoolWalletType): string | null {
    const address = poolType === 'BURN_POOL' ? this.burnPoolAddress : this.miningPoolAddress;
    return address || null;
  }

  /**
   * 检查池钱包是否已配置
   */
  isPoolWalletConfigured(poolType: PoolWalletType, chainType: ChainTypeEnum): boolean {
    try {
      this.rpcProviderManager.getProvider(chainType);
      if (poolType === 'BURN_POOL') {
        return !!this.burnPoolAddress && !!this.mpcSigningClient?.isBurnPoolConfigured();
      } else {
        return !!this.miningPoolAddress && !!this.mpcSigningClient?.isMiningPoolConfigured();
      }
    } catch {
      return false;
    }
  }

  /**
   * 获取池钱包的 fUSDT 链上余额
   */
  async getPoolWalletTokenBalance(chainType: ChainTypeEnum, poolType: PoolWalletType): Promise<string> {
    const provider = this.getProvider(chainType);
    const walletAddress = poolType === 'BURN_POOL' ? this.burnPoolAddress : this.miningPoolAddress;
    const poolName = poolType === 'BURN_POOL' ? '100亿销毁池' : '200万挖矿池';

    if (!walletAddress) {
      throw new Error(`${poolName} wallet address not configured`);
    }

    const contractAddress = this.getTokenContract(chainType, 'FUSDT');
    if (!contractAddress) {
      throw new Error(`fUSDT not configured for chain ${chainType}`);
    }

    const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);
    const balance = await contract.balanceOf(walletAddress);
    const decimals = await contract.decimals();

    return formatUnits(balance, decimals);
  }

  /**
   * 池账户 fUSDT 转账（使用池钱包 MPC 签名）
   */
  async transferTokenAsPoolAccount(
    chainType: ChainTypeEnum,
    poolType: PoolWalletType,
    toAddress: string,
    amount: string,
  ): Promise<TransferResult> {
    const isBurnPool = poolType === 'BURN_POOL';
    const walletAddress = isBurnPool ? this.burnPoolAddress : this.miningPoolAddress;
    const poolName = isBurnPool ? '100亿销毁池' : '200万挖矿池';

    this.logger.log(`[POOL-TRANSFER] Starting fUSDT ${poolName} transfer`);
    this.logger.log(`[POOL-TRANSFER] From: ${walletAddress}`);
    this.logger.log(`[POOL-TRANSFER] To: ${toAddress}`);
    this.logger.log(`[POOL-TRANSFER] Amount: ${amount} fUSDT`);

    const provider = this.getProvider(chainType);

    // 检查钱包是否配置
    if (isBurnPool) {
      if (!this.mpcSigningClient || !this.mpcSigningClient.isBurnPoolConfigured()) {
        const error = 'Burn Pool MPC signing not configured';
        this.logger.error(`[POOL-TRANSFER] ${error}`);
        return { success: false, error };
      }
    } else {
      if (!this.mpcSigningClient || !this.mpcSigningClient.isMiningPoolConfigured()) {
        const error = 'Mining Pool MPC signing not configured';
        this.logger.error(`[POOL-TRANSFER] ${error}`);
        return { success: false, error };
      }
    }

    if (!walletAddress) {
      const error = `${poolName} wallet address not configured`;
      this.logger.error(`[POOL-TRANSFER] ${error}`);
      return { success: false, error };
    }

    try {
      const config = this.chainConfig.getConfig(ChainType.fromEnum(chainType));
      const contractAddress = this.getTokenContract(chainType, 'FUSDT');

      if (!contractAddress) {
        const error = `fUSDT not configured for chain ${chainType}`;
        this.logger.error(`[POOL-TRANSFER] ${error}`);
        return { success: false, error };
      }

      const contract = new Contract(contractAddress, ERC20_TRANSFER_ABI, provider);

      const decimals = await contract.decimals();
      const amountInWei = parseUnits(amount, decimals);

      // 检查余额
      const balance = await contract.balanceOf(walletAddress);
      this.logger.log(`[POOL-TRANSFER] ${poolName} balance: ${formatUnits(balance, decimals)} fUSDT`);

      if (balance < amountInWei) {
        const error = `Insufficient fUSDT balance in ${poolName} wallet`;
        this.logger.error(`[POOL-TRANSFER] ${error}`);
        return { success: false, error };
      }

      // 构建交易
      const nonce = await provider.getTransactionCount(walletAddress);
      const feeData = await provider.getFeeData();
      const transferData = contract.interface.encodeFunctionData('transfer', [toAddress, amountInWei]);

      const gasEstimate = await provider.estimateGas({
        from: walletAddress,
        to: contractAddress,
        data: transferData,
      });
      const gasLimit = gasEstimate * BigInt(120) / BigInt(100);

      const supportsEip1559 = feeData.maxFeePerGas && feeData.maxFeePerGas > BigInt(0);

      let tx: Transaction;
      if (supportsEip1559) {
        tx = Transaction.from({
          type: 2,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          maxFeePerGas: feeData.maxFeePerGas,
          maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        });
      } else {
        const gasPrice = feeData.gasPrice || BigInt(1000000000);
        tx = Transaction.from({
          type: 0,
          chainId: config.chainId,
          nonce,
          to: contractAddress,
          data: transferData,
          gasLimit,
          gasPrice,
        });
      }

      const unsignedTxHash = tx.unsignedHash;

      // 使用对应的池钱包 MPC 签名
      this.logger.log(`[POOL-TRANSFER] Requesting ${poolName} MPC signature...`);
      const signatureHex = isBurnPool
        ? await this.mpcSigningClient!.signMessageAsBurnPool(unsignedTxHash)
        : await this.mpcSigningClient!.signMessageAsMiningPool(unsignedTxHash);

      // 解析签名
      const normalizedSig = signatureHex.startsWith('0x') ? signatureHex : `0x${signatureHex}`;
      const sigBytes = normalizedSig.slice(2);
      const r = `0x${sigBytes.slice(0, 64)}`;
      const s = `0x${sigBytes.slice(64, 128)}`;

      let signature: Signature | null = null;
      for (const yParity of [0, 1] as const) {
        try {
          const testSig = Signature.from({ r, s, yParity });
          const recoveredAddress = recoverAddress(unsignedTxHash, testSig);
          if (recoveredAddress.toLowerCase() === walletAddress.toLowerCase()) {
            signature = testSig;
            break;
          }
        } catch (e) {
          this.logger.debug(`[POOL-TRANSFER] yParity=${yParity} failed: ${e}`);
        }
      }

      if (!signature) {
        throw new Error('Failed to recover correct signature - address mismatch');
      }

      const signedTx = tx.clone();
      signedTx.signature = signature;

      this.logger.log(`[POOL-TRANSFER] Broadcasting transaction...`);
      const txResponse = await provider.broadcastTransaction(signedTx.serialized);
      this.logger.log(`[POOL-TRANSFER] Transaction sent: ${txResponse.hash}`);

      const receipt = await txResponse.wait();

      if (receipt && receipt.status === 1) {
        this.logger.log(`[POOL-TRANSFER] Transaction confirmed! Block: ${receipt.blockNumber}`);
        this.rpcProviderManager.reportSuccess(chainType);
        return {
          success: true,
          txHash: txResponse.hash,
          gasUsed: receipt.gasUsed.toString(),
          blockNumber: receipt.blockNumber,
        };
      } else {
        return { success: false, txHash: txResponse.hash, error: 'Transaction failed (reverted)' };
      }
    } catch (error: any) {
      if (this.isRpcConnectionError(error)) {
        this.rpcProviderManager.reportFailure(chainType, error);
      }
      this.logger.error(`[POOL-TRANSFER] Transfer failed:`, error);
      return {
        success: false,
        error: error.message || 'Unknown error during transfer',
      };
    }
  }
}
