feat: 添加最大仓位限制配置功能

后端变更:
- 添加最大仓位金额(maxPositionValue)和最大仓位数量(maxPositionCount)配置字段
- 实现按市场检查仓位限制的过滤逻辑
- 添加数据库迁移脚本 V11__add_max_position_config.sql

前端变更:
- 重构账户导入和Leader添加为可复用组件(AccountImportForm, LeaderAddForm)
- 在CopyTradingAdd页面集成账户导入和Leader添加Modal
- 在CopyTradingAdd/CopyTradingEdit页面添加最大仓位限制配置项
- 补充所有多语言文件中的缺失键,确保zh-CN/zh-TW/en三种语言文件一致

功能说明:
- 支持设置单个市场的最大仓位金额限制(USDC)
- 支持设置单个市场的最大仓位数量限制
- 两个限制可以同时启用,下单前会检查当前市场仓位是否超过限制
This commit is contained in:
WrBug
2025-12-23 00:56:04 +08:00
parent 20acc72ed6
commit c20e0138df
18 changed files with 1077 additions and 429 deletions
+12 -294
View File
@@ -1,150 +1,20 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Form, Input, Button, message, Typography, Radio, Space, Alert } from 'antd'
import { Card, Form, Button, Typography } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import { useAccountStore } from '../store/accountStore'
import {
getAddressFromPrivateKey,
getAddressFromMnemonic,
getPrivateKeyFromMnemonic,
isValidWalletAddress,
isValidPrivateKey,
isValidMnemonic
} from '../utils'
import { useMediaQuery } from 'react-responsive'
import { message } from 'antd'
import AccountImportForm from '../components/AccountImportForm'
const { Title } = Typography
type ImportType = 'privateKey' | 'mnemonic'
const AccountImport: React.FC = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const isMobile = useMediaQuery({ maxWidth: 768 })
const { importAccount, loading } = useAccountStore()
const [form] = Form.useForm()
const [importType, setImportType] = useState<ImportType>('privateKey')
const [derivedAddress, setDerivedAddress] = useState<string>('')
const [addressError, setAddressError] = useState<string>('')
// 当私钥输入时,自动推导地址
const handlePrivateKeyChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const privateKey = e.target.value.trim()
if (!privateKey) {
setDerivedAddress('')
setAddressError('')
return
}
// 验证私钥格式
if (!isValidPrivateKey(privateKey)) {
setAddressError(t('accountImport.privateKeyInvalid'))
setDerivedAddress('')
return
}
try {
const address = getAddressFromPrivateKey(privateKey)
setDerivedAddress(address)
setAddressError('')
// 自动填充钱包地址字段
form.setFieldsValue({ walletAddress: address })
} catch (error: any) {
setAddressError(error.message || t('accountImport.addressError'))
setDerivedAddress('')
}
}
// 当助记词输入时,自动推导地址
const handleMnemonicChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const mnemonic = e.target.value.trim()
if (!mnemonic) {
setDerivedAddress('')
setAddressError('')
return
}
// 验证助记词格式
if (!isValidMnemonic(mnemonic)) {
setAddressError(t('accountImport.mnemonicInvalid'))
setDerivedAddress('')
return
}
try {
const address = getAddressFromMnemonic(mnemonic, 0)
setDerivedAddress(address)
setAddressError('')
// 自动填充钱包地址字段
form.setFieldsValue({ walletAddress: address })
} catch (error: any) {
setAddressError(error.message || t('accountImport.addressErrorMnemonic'))
setDerivedAddress('')
}
}
const handleSubmit = async (values: any) => {
try {
let privateKey: string
let walletAddress: string
if (importType === 'privateKey') {
// 私钥模式
privateKey = values.privateKey
walletAddress = values.walletAddress
// 验证推导的地址和输入的地址是否一致
if (derivedAddress && walletAddress !== derivedAddress) {
message.error(t('accountImport.walletAddressMismatch'))
return
}
} else {
// 助记词模式
if (!values.mnemonic) {
message.error(t('accountImport.mnemonicRequired'))
return
}
// 从助记词导出私钥和地址
privateKey = getPrivateKeyFromMnemonic(values.mnemonic, 0)
const derivedAddressFromMnemonic = getAddressFromMnemonic(values.mnemonic, 0)
// 如果用户手动输入了地址,验证是否与推导的地址一致
if (values.walletAddress) {
if (values.walletAddress !== derivedAddressFromMnemonic) {
// 地址不匹配,使用推导的地址(因为私钥是从助记词导出的,必须使用对应的地址)
message.warning(`${t('accountImport.walletAddressMismatchMnemonic')}: ${derivedAddressFromMnemonic}`)
walletAddress = derivedAddressFromMnemonic
} else {
// 地址匹配,使用用户输入的地址
walletAddress = values.walletAddress
}
} else {
// 如果用户没有输入地址,使用推导的地址
walletAddress = derivedAddressFromMnemonic
}
}
// 验证钱包地址格式
if (!isValidWalletAddress(walletAddress)) {
message.error(t('accountImport.walletAddressInvalid'))
return
}
await importAccount({
privateKey: privateKey,
walletAddress: walletAddress,
accountName: values.accountName
})
message.success(t('accountImport.importSuccess'))
navigate('/accounts')
} catch (error: any) {
message.error(error.message || t('accountImport.importFailed'))
}
const handleSuccess = async (accountId?: number) => {
message.success(t('accountImport.importSuccess'))
navigate('/accounts')
}
return (
@@ -161,165 +31,13 @@ const AccountImport: React.FC = () => {
</div>
<Card>
<Alert
message={t('accountImport.securityTip')}
description={t('accountImport.securityTipDesc')}
type="warning"
showIcon
style={{ marginBottom: '24px' }}
/>
<Form
<AccountImportForm
form={form}
layout="vertical"
onFinish={handleSubmit}
size={isMobile ? 'middle' : 'large'}
>
<Form.Item label={t('accountImport.importMethod')}>
<Radio.Group
value={importType}
onChange={(e) => {
setImportType(e.target.value)
setDerivedAddress('')
setAddressError('')
form.setFieldsValue({ walletAddress: '' })
}}
>
<Radio value="privateKey">{t('accountImport.privateKey')}</Radio>
<Radio value="mnemonic">{t('accountImport.mnemonic')}</Radio>
</Radio.Group>
</Form.Item>
{importType === 'privateKey' ? (
<>
<Form.Item
label={t('accountImport.privateKeyLabel')}
name="privateKey"
rules={[
{ required: true, message: t('accountImport.privateKeyRequired') },
{
validator: (_, value) => {
if (!value) return Promise.resolve()
if (!isValidPrivateKey(value)) {
return Promise.reject(new Error(t('accountImport.privateKeyInvalid')))
}
return Promise.resolve()
}
}
]}
help={addressError || (derivedAddress ? `${t('accountImport.derivedAddress')}: ${derivedAddress}` : '')}
validateStatus={addressError ? 'error' : derivedAddress ? 'success' : ''}
>
<Input.TextArea
rows={3}
placeholder={t('accountImport.privateKeyPlaceholder')}
onChange={handlePrivateKeyChange}
/>
</Form.Item>
<Form.Item
label={t('accountImport.walletAddress')}
name="walletAddress"
rules={[
{ required: true, message: t('accountImport.walletAddressRequired') },
{
validator: (_, value) => {
if (!value) return Promise.resolve()
if (!isValidWalletAddress(value)) {
return Promise.reject(new Error(t('accountImport.walletAddressInvalid')))
}
if (derivedAddress && value !== derivedAddress) {
return Promise.reject(new Error(t('accountImport.walletAddressMismatch')))
}
return Promise.resolve()
}
}
]}
>
<Input
placeholder={t('accountImport.walletAddressPlaceholder')}
readOnly={!!derivedAddress}
/>
</Form.Item>
</>
) : (
<>
<Form.Item
label={t('accountImport.mnemonicLabel')}
name="mnemonic"
rules={[
{ required: true, message: t('accountImport.mnemonicRequired') },
{
validator: (_, value) => {
if (!value) return Promise.resolve()
if (!isValidMnemonic(value)) {
return Promise.reject(new Error(t('accountImport.mnemonicInvalid')))
}
return Promise.resolve()
}
}
]}
help={addressError || (derivedAddress ? `${t('accountImport.derivedAddress')}: ${derivedAddress}` : '')}
validateStatus={addressError ? 'error' : derivedAddress ? 'success' : ''}
>
<Input.TextArea
rows={4}
placeholder={t('accountImport.mnemonicPlaceholder')}
onChange={handleMnemonicChange}
/>
</Form.Item>
<Form.Item
label={t('accountImport.walletAddress')}
name="walletAddress"
rules={[
{ required: true, message: t('accountImport.walletAddressRequired') },
{
validator: (_, value) => {
if (!value) return Promise.resolve()
if (!isValidWalletAddress(value)) {
return Promise.reject(new Error(t('accountImport.walletAddressInvalid')))
}
if (derivedAddress && value !== derivedAddress) {
return Promise.reject(new Error(t('accountImport.walletAddressMismatchMnemonic')))
}
return Promise.resolve()
}
}
]}
>
<Input
placeholder={t('accountImport.walletAddressPlaceholder')}
readOnly={!!derivedAddress}
/>
</Form.Item>
</>
)}
<Form.Item
label={t('accountImport.accountName')}
name="accountName"
>
<Input placeholder={t('accountImport.accountNamePlaceholder')} />
</Form.Item>
<Form.Item>
<Space>
<Button
type="primary"
htmlType="submit"
loading={loading}
size={isMobile ? 'middle' : 'large'}
>
{t('accountImport.importAccount')}
</Button>
<Button onClick={() => navigate('/accounts')}>
{t('common.cancel')}
</Button>
</Space>
</Form.Item>
</Form>
onSuccess={handleSuccess}
onCancel={() => navigate('/accounts')}
showAlert={true}
showCancelButton={true}
/>
</Card>
</div>
)
+168 -4
View File
@@ -1,12 +1,15 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Form, Button, Switch, message, Typography, Space, Radio, InputNumber, Modal, Table, Select, Divider, Input } from 'antd'
import { ArrowLeftOutlined, SaveOutlined, FileTextOutlined } from '@ant-design/icons'
import { ArrowLeftOutlined, SaveOutlined, FileTextOutlined, PlusOutlined } from '@ant-design/icons'
import { apiService } from '../services/api'
import { useAccountStore } from '../store/accountStore'
import type { Leader, CopyTradingTemplate, CopyTradingCreateRequest } from '../types'
import { formatUSDC } from '../utils'
import { useTranslation } from 'react-i18next'
import { useMediaQuery } from 'react-responsive'
import AccountImportForm from '../components/AccountImportForm'
import LeaderAddForm from '../components/LeaderAddForm'
const { Title } = Typography
const { Option } = Select
@@ -14,6 +17,7 @@ const { Option } = Select
const CopyTradingAdd: React.FC = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const isMobile = useMediaQuery({ maxWidth: 768 })
const { accounts, fetchAccounts } = useAccountStore()
const [form] = Form.useForm()
const [loading, setLoading] = useState(false)
@@ -22,6 +26,14 @@ const CopyTradingAdd: React.FC = () => {
const [templateModalVisible, setTemplateModalVisible] = useState(false)
const [copyMode, setCopyMode] = useState<'RATIO' | 'FIXED'>('RATIO')
// 导入账户modal相关状态
const [accountImportModalVisible, setAccountImportModalVisible] = useState(false)
const [accountImportForm] = Form.useForm()
// 添加leader modal相关状态
const [leaderAddModalVisible, setLeaderAddModalVisible] = useState(false)
const [leaderAddForm] = Form.useForm()
// 生成默认配置名
const generateDefaultConfigName = (): string => {
const now = new Date()
@@ -85,7 +97,9 @@ const CopyTradingAdd: React.FC = () => {
minOrderDepth: template.minOrderDepth ? parseFloat(template.minOrderDepth) : undefined,
maxSpread: template.maxSpread ? parseFloat(template.maxSpread) : undefined,
minPrice: template.minPrice ? parseFloat(template.minPrice) : undefined,
maxPrice: template.maxPrice ? parseFloat(template.maxPrice) : undefined
maxPrice: template.maxPrice ? parseFloat(template.maxPrice) : undefined,
maxPositionValue: (template as any).maxPositionValue ? parseFloat((template as any).maxPositionValue) : undefined,
maxPositionCount: (template as any).maxPositionCount
})
setCopyMode(template.copyMode)
setTemplateModalVisible(false)
@@ -96,6 +110,36 @@ const CopyTradingAdd: React.FC = () => {
setCopyMode(mode)
}
// 处理导入账户成功
const handleAccountImportSuccess = async (accountId: number) => {
message.success(t('accountImport.importSuccess'))
// 刷新账户列表
await fetchAccounts()
// 自动选择新添加的账户
form.setFieldsValue({ accountId })
// 关闭modal并重置表单
setAccountImportModalVisible(false)
accountImportForm.resetFields()
}
// 处理添加leader成功
const handleLeaderAddSuccess = async (leaderId: number) => {
message.success(t('leaderAdd.addSuccess') || '添加 Leader 成功')
// 刷新leader列表
await fetchLeaders()
// 自动选择新添加的leader
form.setFieldsValue({ leaderId })
// 关闭modal并重置表单
setLeaderAddModalVisible(false)
leaderAddForm.resetFields()
}
const handleSubmit = async (values: any) => {
// 前端校验
if (values.copyMode === 'FIXED') {
@@ -134,6 +178,8 @@ const CopyTradingAdd: React.FC = () => {
maxSpread: values.maxSpread?.toString(),
minPrice: values.minPrice?.toString(),
maxPrice: values.maxPrice?.toString(),
maxPositionValue: values.maxPositionValue?.toString(),
maxPositionCount: values.maxPositionCount,
configName: values.configName?.trim(),
pushFailedOrders: values.pushFailedOrders ?? false
}
@@ -209,7 +255,24 @@ const CopyTradingAdd: React.FC = () => {
name="accountId"
rules={[{ required: true, message: t('copyTradingAdd.walletRequired') || '请选择钱包' }]}
>
<Select placeholder={t('copyTradingAdd.selectWalletPlaceholder') || '请选择钱包'}>
<Select
placeholder={t('copyTradingAdd.selectWalletPlaceholder') || '请选择钱包'}
notFoundContent={
accounts.length === 0 ? (
<div style={{ textAlign: 'center', padding: '12px' }}>
<div style={{ marginBottom: '8px' }}>{t('copyTradingAdd.noAccounts') || '暂无账户'}</div>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => setAccountImportModalVisible(true)}
size="small"
>
{t('copyTradingAdd.importAccount') || '导入账户'}
</Button>
</div>
) : null
}
>
{accounts.map(account => (
<Option key={account.id} value={account.id}>
{account.accountName || `账户 ${account.id}`} ({account.walletAddress.slice(0, 6)}...{account.walletAddress.slice(-4)})
@@ -223,7 +286,24 @@ const CopyTradingAdd: React.FC = () => {
name="leaderId"
rules={[{ required: true, message: t('copyTradingAdd.leaderRequired') || '请选择 Leader' }]}
>
<Select placeholder={t('copyTradingAdd.selectLeaderPlaceholder') || '请选择 Leader'}>
<Select
placeholder={t('copyTradingAdd.selectLeaderPlaceholder') || '请选择 Leader'}
notFoundContent={
leaders.length === 0 ? (
<div style={{ textAlign: 'center', padding: '12px' }}>
<div style={{ marginBottom: '8px' }}>{t('copyTradingAdd.noLeaders') || '暂无 Leader'}</div>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => setLeaderAddModalVisible(true)}
size="small"
>
{t('copyTradingAdd.addLeader') || '添加 Leader'}
</Button>
</div>
) : null
}
>
{leaders.map(leader => (
<Option key={leader.id} value={leader.id}>
{leader.leaderName || `Leader ${leader.id}`} ({leader.leaderAddress.slice(0, 6)}...{leader.leaderAddress.slice(-4)})
@@ -467,6 +547,35 @@ const CopyTradingAdd: React.FC = () => {
</Input.Group>
</Form.Item>
<Divider>{t('copyTradingAdd.positionLimitFilter') || '最大仓位限制'}</Divider>
<Form.Item
label={t('copyTradingAdd.maxPositionValue') || '最大仓位金额 (USDC)'}
name="maxPositionValue"
tooltip={t('copyTradingAdd.maxPositionValueTooltip') || '限制单个市场的最大仓位金额。如果该市场的当前仓位金额 + 跟单金额超过此限制,则不会下单。不填写则不启用此限制'}
>
<InputNumber
min={0}
step={0.0001}
precision={4}
style={{ width: '100%' }}
placeholder={t('copyTradingAdd.maxPositionValuePlaceholder') || '例如:100(可选,不填写表示不启用)'}
/>
</Form.Item>
<Form.Item
label={t('copyTradingAdd.maxPositionCount') || '最大仓位数量'}
name="maxPositionCount"
tooltip={t('copyTradingAdd.maxPositionCountTooltip') || '限制单个市场的最大仓位数量。如果该市场的当前仓位数量达到或超过此限制,则不会下单。不填写则不启用此限制'}
>
<InputNumber
min={1}
step={1}
style={{ width: '100%' }}
placeholder={t('copyTradingAdd.maxPositionCountPlaceholder') || '例如:10(可选,不填写表示不启用)'}
/>
</Form.Item>
<Divider>{t('copyTradingAdd.advancedSettings') || '高级设置'}</Divider>
{/* 跟单卖出 */}
@@ -550,6 +659,61 @@ const CopyTradingAdd: React.FC = () => {
]}
/>
</Modal>
{/* 导入账户 Modal */}
<Modal
title={t('accountImport.title') || '导入账户'}
open={accountImportModalVisible}
onCancel={() => {
setAccountImportModalVisible(false)
accountImportForm.resetFields()
}}
footer={null}
width={isMobile ? '95%' : 600}
style={{ top: isMobile ? 20 : 50 }}
bodyStyle={{ padding: '24px', maxHeight: 'calc(100vh - 150px)', overflow: 'auto' }}
destroyOnClose
maskClosable
closable
>
<AccountImportForm
form={accountImportForm}
onSuccess={handleAccountImportSuccess}
onCancel={() => {
setAccountImportModalVisible(false)
accountImportForm.resetFields()
}}
showAlert={true}
showCancelButton={true}
/>
</Modal>
{/* 添加 Leader Modal */}
<Modal
title={t('leaderAdd.title') || '添加 Leader'}
open={leaderAddModalVisible}
onCancel={() => {
setLeaderAddModalVisible(false)
leaderAddForm.resetFields()
}}
footer={null}
width={isMobile ? '95%' : 600}
style={{ top: isMobile ? 20 : 50 }}
bodyStyle={{ padding: '24px', maxHeight: 'calc(100vh - 150px)', overflow: 'auto' }}
destroyOnClose
maskClosable
closable
>
<LeaderAddForm
form={leaderAddForm}
onSuccess={handleLeaderAddSuccess}
onCancel={() => {
setLeaderAddModalVisible(false)
leaderAddForm.resetFields()
}}
showCancelButton={true}
/>
</Modal>
</div>
)
}
+33
View File
@@ -58,6 +58,8 @@ const CopyTradingEdit: React.FC = () => {
maxSpread: found.maxSpread ? parseFloat(found.maxSpread) : undefined,
minPrice: found.minPrice ? parseFloat(found.minPrice) : undefined,
maxPrice: found.maxPrice ? parseFloat(found.maxPrice) : undefined,
maxPositionValue: found.maxPositionValue ? parseFloat(found.maxPositionValue) : undefined,
maxPositionCount: found.maxPositionCount,
configName: found.configName || '',
pushFailedOrders: found.pushFailedOrders ?? false
})
@@ -123,6 +125,8 @@ const CopyTradingEdit: React.FC = () => {
maxSpread: values.maxSpread?.toString(),
minPrice: values.minPrice?.toString(),
maxPrice: values.maxPrice?.toString(),
maxPositionValue: values.maxPositionValue?.toString(),
maxPositionCount: values.maxPositionCount,
configName: values.configName?.trim() || undefined,
pushFailedOrders: values.pushFailedOrders
}
@@ -436,6 +440,35 @@ const CopyTradingEdit: React.FC = () => {
</Input.Group>
</Form.Item>
<Divider>{t('copyTradingEdit.positionLimitFilter') || '最大仓位限制'}</Divider>
<Form.Item
label={t('copyTradingEdit.maxPositionValue') || '最大仓位金额 (USDC)'}
name="maxPositionValue"
tooltip={t('copyTradingEdit.maxPositionValueTooltip') || '限制单个市场的最大仓位金额。如果该市场的当前仓位金额 + 跟单金额超过此限制,则不会下单。不填写则不启用此限制'}
>
<InputNumber
min={0}
step={0.0001}
precision={4}
style={{ width: '100%' }}
placeholder={t('copyTradingEdit.maxPositionValuePlaceholder') || '例如:100(可选,不填写表示不启用)'}
/>
</Form.Item>
<Form.Item
label={t('copyTradingEdit.maxPositionCount') || '最大仓位数量'}
name="maxPositionCount"
tooltip={t('copyTradingEdit.maxPositionCountTooltip') || '限制单个市场的最大仓位数量。如果该市场的当前仓位数量达到或超过此限制,则不会下单。不填写则不启用此限制'}
>
<InputNumber
min={1}
step={1}
style={{ width: '100%' }}
placeholder={t('copyTradingEdit.maxPositionCountPlaceholder') || '例如:10(可选,不填写表示不启用)'}
/>
</Form.Item>
<Divider>{t('copyTradingEdit.advancedSettings') || '高级设置'}</Divider>
{/* 跟单卖出 */}
@@ -65,6 +65,8 @@ const EditModal: React.FC<EditModalProps> = ({
maxSpread: found.maxSpread ? parseFloat(found.maxSpread) : undefined,
minPrice: found.minPrice ? parseFloat(found.minPrice) : undefined,
maxPrice: found.maxPrice ? parseFloat(found.maxPrice) : undefined,
maxPositionValue: found.maxPositionValue ? parseFloat(found.maxPositionValue) : undefined,
maxPositionCount: found.maxPositionCount,
configName: found.configName || '',
pushFailedOrders: found.pushFailedOrders ?? false
})
@@ -129,6 +131,8 @@ const EditModal: React.FC<EditModalProps> = ({
maxSpread: values.maxSpread?.toString(),
minPrice: values.minPrice?.toString(),
maxPrice: values.maxPrice?.toString(),
maxPositionValue: values.maxPositionValue?.toString(),
maxPositionCount: values.maxPositionCount,
configName: values.configName?.trim() || undefined,
pushFailedOrders: values.pushFailedOrders
}
@@ -436,6 +440,35 @@ const EditModal: React.FC<EditModalProps> = ({
</Input.Group>
</Form.Item>
<Divider>{t('copyTradingEdit.positionLimitFilter') || '最大仓位限制'}</Divider>
<Form.Item
label={t('copyTradingEdit.maxPositionValue') || '最大仓位金额 (USDC)'}
name="maxPositionValue"
tooltip={t('copyTradingEdit.maxPositionValueTooltip') || '限制单个市场的最大仓位金额。如果该市场的当前仓位金额 + 跟单金额超过此限制,则不会下单。不填写则不启用此限制'}
>
<InputNumber
min={0}
step={0.0001}
precision={4}
style={{ width: '100%' }}
placeholder={t('copyTradingEdit.maxPositionValuePlaceholder') || '例如:100(可选,不填写表示不启用)'}
/>
</Form.Item>
<Form.Item
label={t('copyTradingEdit.maxPositionCount') || '最大仓位数量'}
name="maxPositionCount"
tooltip={t('copyTradingEdit.maxPositionCountTooltip') || '限制单个市场的最大仓位数量。如果该市场的当前仓位数量达到或超过此限制,则不会下单。不填写则不启用此限制'}
>
<InputNumber
min={1}
step={1}
style={{ width: '100%' }}
placeholder={t('copyTradingEdit.maxPositionCountPlaceholder') || '例如:10(可选,不填写表示不启用)'}
/>
</Form.Item>
<Divider>{t('copyTradingEdit.advancedSettings') || '高级设置'}</Divider>
<Form.Item
+12 -110
View File
@@ -1,42 +1,20 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Form, Input, Button, message, Typography, Space } from 'antd'
import { Card, Form, Button, Typography } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { apiService } from '../services/api'
import { useMediaQuery } from 'react-responsive'
import { useTranslation } from 'react-i18next'
import { isValidWalletAddress } from '../utils'
import { message } from 'antd'
import LeaderAddForm from '../components/LeaderAddForm'
const { Title } = Typography
const LeaderAdd: React.FC = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const isMobile = useMediaQuery({ maxWidth: 768 })
const [form] = Form.useForm()
const [loading, setLoading] = useState(false)
const handleSubmit = async (values: any) => {
setLoading(true)
try {
const response = await apiService.leaders.add({
leaderAddress: values.leaderAddress.trim(),
leaderName: values.leaderName?.trim() || undefined,
remark: values.remark?.trim() || undefined,
website: values.website?.trim() || undefined
})
if (response.data.code === 0) {
message.success(t('leaderAdd.addSuccess') || '添加 Leader 成功')
navigate('/leaders')
} else {
message.error(response.data.msg || t('leaderAdd.addFailed') || '添加 Leader 失败')
}
} catch (error: any) {
message.error(error.message || t('leaderAdd.addFailed') || '添加 Leader 失败')
} finally {
setLoading(false)
}
const handleSuccess = async () => {
message.success(t('leaderAdd.addSuccess') || '添加 Leader 成功')
navigate('/leaders')
}
return (
@@ -47,94 +25,18 @@ const LeaderAdd: React.FC = () => {
onClick={() => navigate('/leaders')}
style={{ marginBottom: '16px' }}
>
{t('leaderAdd.back') || '返回'}
</Button>
<Title level={2} style={{ margin: 0 }}>{t('leaderAdd.title') || '添加 Leader'}</Title>
</div>
<Card>
<Form
<LeaderAddForm
form={form}
layout="vertical"
onFinish={handleSubmit}
size={isMobile ? 'middle' : 'large'}
initialValues={{
enabled: true
}}
>
<Form.Item
label={t('leaderAdd.leaderAddress') || 'Leader 钱包地址'}
name="leaderAddress"
rules={[
{ required: true, message: t('leaderAdd.leaderAddressRequired') || '请输入 Leader 钱包地址' },
{
validator: (_, value) => {
if (!value) {
return Promise.reject(new Error(t('leaderAdd.leaderAddressRequired') || '请输入 Leader 钱包地址'))
}
if (!isValidWalletAddress(value.trim())) {
return Promise.reject(new Error(t('leaderAdd.leaderAddressInvalid') || '钱包地址格式不正确(必须是 0x 开头的 42 位地址)'))
}
return Promise.resolve()
}
}
]}
tooltip={t('leaderAdd.leaderAddressTooltip') || '被跟单者的钱包地址,系统将监控该地址的交易并自动跟单'}
>
<Input placeholder="0x..." style={{ fontFamily: 'monospace' }} />
</Form.Item>
<Form.Item
label={t('leaderAdd.leaderName') || 'Leader 名称'}
name="leaderName"
tooltip={t('leaderAdd.leaderNameTooltip') || '可选,用于标识 Leader,方便管理'}
>
<Input placeholder={t('leaderAdd.leaderNamePlaceholder') || '可选,用于标识 Leader'} />
</Form.Item>
<Form.Item
label={t('leaderAdd.remark') || 'Leader 备注'}
name="remark"
tooltip={t('leaderAdd.remarkTooltip') || '可选,用于记录 Leader 的备注信息'}
>
<Input.TextArea
placeholder={t('leaderAdd.remarkPlaceholder') || '可选,用于记录 Leader 的备注信息'}
rows={3}
maxLength={500}
showCount
/>
</Form.Item>
<Form.Item
label={t('leaderAdd.website') || 'Leader 网站'}
name="website"
tooltip={t('leaderAdd.websiteTooltip') || '可选,Leader 的网站链接'}
rules={[
{
type: 'url',
message: t('leaderAdd.websiteInvalid') || '请输入有效的 URL 地址'
}
]}
>
<Input placeholder={t('leaderAdd.websitePlaceholder') || '可选,例如:https://example.com'} />
</Form.Item>
<Form.Item>
<Space>
<Button
type="primary"
htmlType="submit"
loading={loading}
size={isMobile ? 'middle' : 'large'}
>
{t('leaderAdd.add') || '添加 Leader'}
</Button>
<Button onClick={() => navigate('/leaders')}>
{t('leaderAdd.cancel') || '取消'}
</Button>
</Space>
</Form.Item>
</Form>
onSuccess={handleSuccess}
onCancel={() => navigate('/leaders')}
showCancelButton={true}
/>
</Card>
</div>
)