import React, { useState, useEffect } from 'react' import type { Exchange } from '../../types' import { t, type Language } from '../../i18n/translations' import { api } from '../../lib/api' import { getExchangeIcon } from '../ExchangeIcons' import { TwoStageKeyModal, type TwoStageKeyModalResult, } from '../TwoStageKeyModal' import { WebCryptoEnvironmentCheck, type WebCryptoCheckStatus, } from '../WebCryptoEnvironmentCheck' import { BookOpen, Trash2, HelpCircle } from 'lucide-react' import { toast } from 'sonner' import { Tooltip } from './Tooltip' import { getShortName } from './utils' interface ExchangeConfigModalProps { allExchanges: Exchange[] editingExchangeId: string | null onSave: ( exchangeId: string, apiKey: string, secretKey?: string, testnet?: boolean, hyperliquidWalletAddr?: string, asterUser?: string, asterSigner?: string, asterPrivateKey?: string, lighterWalletAddr?: string, lighterPrivateKey?: string, lighterApiKeyPrivateKey?: string ) => Promise onDelete: (exchangeId: string) => void onClose: () => void language: Language } export function ExchangeConfigModal({ allExchanges, editingExchangeId, onSave, onDelete, onClose, language, }: ExchangeConfigModalProps) { const [selectedExchangeId, setSelectedExchangeId] = useState( editingExchangeId || '' ) const [apiKey, setApiKey] = useState('') const [secretKey, setSecretKey] = useState('') const [passphrase, setPassphrase] = useState('') const [testnet, setTestnet] = useState(false) const [showGuide, setShowGuide] = useState(false) const [serverIP, setServerIP] = useState<{ public_ip: string message: string } | null>(null) const [loadingIP, setLoadingIP] = useState(false) const [copiedIP, setCopiedIP] = useState(false) const [webCryptoStatus, setWebCryptoStatus] = useState('idle') // 币安配置指南展开状态 const [showBinanceGuide, setShowBinanceGuide] = useState(false) // Aster 特定字段 const [asterUser, setAsterUser] = useState('') const [asterSigner, setAsterSigner] = useState('') const [asterPrivateKey, setAsterPrivateKey] = useState('') // Hyperliquid 特定字段 const [hyperliquidWalletAddr, setHyperliquidWalletAddr] = useState('') // LIGHTER 特定字段 const [lighterWalletAddr, setLighterWalletAddr] = useState('') const [lighterPrivateKey, setLighterPrivateKey] = useState('') const [lighterApiKeyPrivateKey, setLighterApiKeyPrivateKey] = useState('') // 安全输入状态 const [secureInputTarget, setSecureInputTarget] = useState< null | 'hyperliquid' | 'aster' | 'lighter' >(null) // 获取当前编辑的交易所信息 const selectedExchange = allExchanges?.find( (e) => e.id === selectedExchangeId ) // 如果是编辑现有交易所,初始化表单数据 useEffect(() => { if (editingExchangeId && selectedExchange) { setApiKey(selectedExchange.apiKey || '') setSecretKey(selectedExchange.secretKey || '') setPassphrase('') // Don't load existing passphrase for security setTestnet(selectedExchange.testnet || false) // Aster 字段 setAsterUser(selectedExchange.asterUser || '') setAsterSigner(selectedExchange.asterSigner || '') setAsterPrivateKey('') // Don't load existing private key for security // Hyperliquid 字段 setHyperliquidWalletAddr(selectedExchange.hyperliquidWalletAddr || '') // LIGHTER 字段 setLighterWalletAddr(selectedExchange.lighterWalletAddr || '') setLighterPrivateKey('') // Don't load existing private key for security setLighterApiKeyPrivateKey('') // Don't load existing API key for security } }, [editingExchangeId, selectedExchange]) // 加载服务器IP(当选择binance时) useEffect(() => { if (selectedExchangeId === 'binance' && !serverIP) { setLoadingIP(true) api .getServerIP() .then((data) => { setServerIP(data) }) .catch((err) => { console.error('Failed to load server IP:', err) }) .finally(() => { setLoadingIP(false) }) } }, [selectedExchangeId]) const handleCopyIP = async (ip: string) => { try { // 优先使用现代 Clipboard API if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(ip) setCopiedIP(true) setTimeout(() => setCopiedIP(false), 2000) toast.success(t('ipCopied', language)) } else { // 降级方案: 使用传统的 execCommand 方法 const textArea = document.createElement('textarea') textArea.value = ip textArea.style.position = 'fixed' textArea.style.left = '-999999px' textArea.style.top = '-999999px' document.body.appendChild(textArea) textArea.focus() textArea.select() try { const successful = document.execCommand('copy') if (successful) { setCopiedIP(true) setTimeout(() => setCopiedIP(false), 2000) toast.success(t('ipCopied', language)) } else { throw new Error('复制命令执行失败') } } finally { document.body.removeChild(textArea) } } } catch (err) { console.error('复制失败:', err) // 显示错误提示 toast.error( t('copyIPFailed', language) || `复制失败: ${ip}\n请手动复制此IP地址` ) } } // 安全输入处理函数 const secureInputContextLabel = secureInputTarget === 'aster' ? t('asterExchangeName', language) : secureInputTarget === 'hyperliquid' ? t('hyperliquidExchangeName', language) : undefined const handleSecureInputCancel = () => { setSecureInputTarget(null) } const handleSecureInputComplete = ({ value, obfuscationLog, }: TwoStageKeyModalResult) => { const trimmed = value.trim() if (secureInputTarget === 'hyperliquid') { setApiKey(trimmed) } if (secureInputTarget === 'aster') { setAsterPrivateKey(trimmed) } if (secureInputTarget === 'lighter') { setLighterPrivateKey(trimmed) toast.success(t('lighterPrivateKeyImported', language)) } // 仅在开发环境输出调试信息 if (import.meta.env.DEV) { console.log('Secure input obfuscation log:', obfuscationLog) } setSecureInputTarget(null) } // 掩盖敏感数据显示 const maskSecret = (secret: string) => { if (!secret || secret.length === 0) return '' if (secret.length <= 8) return '*'.repeat(secret.length) return ( secret.slice(0, 4) + '*'.repeat(Math.max(secret.length - 8, 4)) + secret.slice(-4) ) } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() if (!selectedExchangeId) return // 根据交易所类型验证不同字段 if (selectedExchange?.id === 'binance') { if (!apiKey.trim() || !secretKey.trim()) return await onSave(selectedExchangeId, apiKey.trim(), secretKey.trim(), testnet) } else if (selectedExchange?.id === 'hyperliquid') { if (!apiKey.trim() || !hyperliquidWalletAddr.trim()) return // 验证私钥和钱包地址 await onSave( selectedExchangeId, apiKey.trim(), '', testnet, hyperliquidWalletAddr.trim() ) } else if (selectedExchange?.id === 'aster') { if (!asterUser.trim() || !asterSigner.trim() || !asterPrivateKey.trim()) return await onSave( selectedExchangeId, '', '', testnet, undefined, asterUser.trim(), asterSigner.trim(), asterPrivateKey.trim() ) } else if (selectedExchange?.id === 'lighter') { if (!lighterWalletAddr.trim() || !lighterPrivateKey.trim()) return await onSave( selectedExchangeId, lighterPrivateKey.trim(), '', testnet, lighterWalletAddr.trim(), undefined, undefined, undefined, lighterWalletAddr.trim(), lighterPrivateKey.trim(), lighterApiKeyPrivateKey.trim() ) } else if (selectedExchange?.id === 'okx') { if (!apiKey.trim() || !secretKey.trim() || !passphrase.trim()) return await onSave(selectedExchangeId, apiKey.trim(), secretKey.trim(), testnet) } else { // 默认情况(其他CEX交易所) if (!apiKey.trim() || !secretKey.trim()) return await onSave(selectedExchangeId, apiKey.trim(), secretKey.trim(), testnet) } } // 可选择的交易所列表(所有支持的交易所) const availableExchanges = allExchanges || [] return (

{editingExchangeId ? t('editExchange', language) : t('addExchange', language)}

{selectedExchange?.id === 'binance' && ( )} {editingExchangeId && ( )}
{!editingExchangeId && (
{t('environmentSteps.checkTitle', language)}
{t('environmentSteps.selectTitle', language)}
)} {selectedExchange && (
{getExchangeIcon(selectedExchange.id, { width: 32, height: 32, })}
{getShortName(selectedExchange.name)}
{selectedExchange.type.toUpperCase()} •{' '} {selectedExchange.id}
)} {selectedExchange && ( <> {/* Binance/Bybit 和其他 CEX 交易所的字段 */} {(selectedExchange.id === 'binance' || selectedExchange.id === 'bybit' || selectedExchange.type === 'cex') && selectedExchange.id !== 'hyperliquid' && selectedExchange.id !== 'aster' && ( <> {/* 币安用户配置提示 (D1 方案) */} {selectedExchange.id === 'binance' && (
setShowBinanceGuide(!showBinanceGuide)} >
ℹ️ 币安用户必读: 使用「现货与合约交易」API,不要用「统一账户 API」
{showBinanceGuide ? '▲' : '▼'}
{/* 展开的详细说明 */} {showBinanceGuide && (
e.stopPropagation()} >

原因:统一账户 API 权限结构不同,会导致订单提交失败

正确配置步骤:

  1. 登录币安 → 个人中心 →{' '} API 管理
  2. 创建 API → 选择「 系统生成的 API 密钥」
  3. 勾选「现货与合约交易」( 不选统一账户 )
  4. IP 限制选「无限制 」或添加服务器 IP

💡 多资产模式用户注意: 如果您开启了多资产模式,将强制使用全仓模式。建议关闭多资产模式以支持逐仓交易。

📖 查看币安官方教程 ↗
)}
)}
setApiKey(e.target.value)} placeholder={t('enterAPIKey', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
setSecretKey(e.target.value)} placeholder={t('enterSecretKey', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
{selectedExchange.id === 'okx' && (
setPassphrase(e.target.value)} placeholder={t('enterPassphrase', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
)} {/* Binance 白名单IP提示 */} {selectedExchange.id === 'binance' && (
{t('whitelistIP', language)}
{t('whitelistIPDesc', language)}
{loadingIP ? (
{t('loadingServerIP', language)}
) : serverIP && serverIP.public_ip ? (
{serverIP.public_ip}
) : null}
)} )} {/* Aster 交易所的字段 */} {selectedExchange.id === 'aster' && ( <>
setAsterUser(e.target.value)} placeholder={t('enterUser', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
setAsterSigner(e.target.value)} placeholder={t('enterSigner', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
setAsterPrivateKey(e.target.value)} placeholder={t('enterPrivateKey', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
)} {/* Hyperliquid 交易所的字段 */} {selectedExchange.id === 'hyperliquid' && ( <> {/* 安全提示 banner */}
🔐
{t('hyperliquidAgentWalletTitle', language)}
{t('hyperliquidAgentWalletDesc', language)}
{/* Agent Private Key 字段 */}
{apiKey && ( )}
{apiKey && (
{t('secureInputHint', language)}
)}
{t('hyperliquidAgentPrivateKeyDesc', language)}
{/* Main Wallet Address 字段 */}
setHyperliquidWalletAddr(e.target.value) } placeholder={t( 'enterHyperliquidMainWalletAddress', language )} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
{t('hyperliquidMainWalletAddressDesc', language)}
)} {/* LIGHTER 特定配置 */} {selectedExchange?.id === 'lighter' && ( <> {/* L1 Wallet Address */}
setLighterWalletAddr(e.target.value)} placeholder={t('enterLighterWalletAddress', language)} className="w-full px-3 py-2 rounded" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
{t('lighterWalletAddressDesc', language)}
{/* L1 Private Key */}
setLighterPrivateKey(e.target.value)} placeholder={t('enterLighterPrivateKey', language)} className="w-full px-3 py-2 rounded font-mono text-sm" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} required />
{t('lighterPrivateKeyDesc', language)}
{/* API Key Private Key */}
setLighterApiKeyPrivateKey(e.target.value)} placeholder={t('enterLighterApiKeyPrivateKey', language)} className="w-full px-3 py-2 rounded font-mono text-sm" style={{ background: '#0B0E11', border: '1px solid #2B3139', color: '#EAECEF', }} />
{t('lighterApiKeyPrivateKeyDesc', language)}
💡 {t('lighterApiKeyOptionalNote', language)}
{/* V1/V2 Status Display */}
{lighterApiKeyPrivateKey ? '✅ LIGHTER V2' : '⚠️ LIGHTER V1'}
{lighterApiKeyPrivateKey ? t('lighterV2Description', language) : t('lighterV1Description', language) }
)} )}
{/* Binance Setup Guide Modal */} {showGuide && (
setShowGuide(false)} >
e.stopPropagation()} >

{t('binanceSetupGuide', language)}

{t('binanceSetupGuide',
)} {/* Two Stage Key Modal */}
) }