123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- #!/usr/bin/env tsx
- /**
- * Pacifica 账户生成示例
- * 演示如何生成、配置和管理多个Pacifica交易账户
- */
- import { ethers } from 'ethers';
- import { promises as fs } from 'fs';
- import path from 'path';
- import crypto from 'crypto';
- // 账户配置接口
- interface AccountConfig {
- name: string;
- privateKey: string;
- initialUSDC: number;
- riskLimits: {
- maxPositionSize: number;
- maxDailyLoss: number;
- maxLeverage: number;
- stopLossThreshold: number;
- maxSlippage: number;
- minMarginRatio: number;
- };
- }
- // 加密工具类
- class EncryptionUtils {
- /**
- * 生成加密密钥
- */
- static generateKey(): string {
- return crypto.randomBytes(32).toString('hex');
- }
- /**
- * 简单的私钥加密(生产环境应使用更安全的方法)
- */
- static encryptPrivateKey(privateKey: string, password: string): string {
- const key = crypto.scryptSync(password, 'salt', 32);
- const iv = crypto.randomBytes(16);
- const cipher = crypto.createCipher('aes-256-cbc', key);
-
- let encrypted = cipher.update(privateKey, 'utf8', 'hex');
- encrypted += cipher.final('hex');
-
- return `${iv.toString('hex')}:${encrypted}`;
- }
- /**
- * 简单的私钥解密(生产环境应使用更安全的方法)
- */
- static decryptPrivateKey(encryptedKey: string, password: string): string {
- const [ivHex, encrypted] = encryptedKey.split(':');
- const key = crypto.scryptSync(password, 'salt', 32);
- const iv = Buffer.from(ivHex, 'hex');
-
- const decipher = crypto.createDecipher('aes-256-cbc', key);
-
- let decrypted = decipher.update(encrypted, 'hex', 'utf8');
- decrypted += decipher.final('utf8');
-
- return decrypted;
- }
- }
- // 账户生成器类
- class AccountGenerator {
- private readonly configDir: string;
- private readonly accountsFile: string;
- constructor(configDir: string = './config') {
- this.configDir = configDir;
- this.accountsFile = path.join(configDir, 'accounts.json');
- }
- /**
- * 生成新的以太坊钱包
- */
- generateWallet(): { address: string; privateKey: string } {
- const wallet = ethers.Wallet.createRandom();
- return {
- address: wallet.address,
- privateKey: wallet.privateKey
- };
- }
- /**
- * 生成账户配置
- */
- generateAccountConfig(
- name: string,
- initialUSDC: number = 10000,
- riskProfile: 'conservative' | 'moderate' | 'aggressive' = 'moderate'
- ): AccountConfig {
- const wallet = this.generateWallet();
-
- // 根据风险偏好设置风险限制
- const riskLimits = this.getRiskLimits(riskProfile);
-
- return {
- name,
- privateKey: wallet.privateKey, // 在实际使用中应该加密
- initialUSDC,
- riskLimits
- };
- }
- /**
- * 获取风险限制配置
- */
- private getRiskLimits(riskProfile: 'conservative' | 'moderate' | 'aggressive') {
- const profiles = {
- conservative: {
- maxPositionSize: 0.05, // 5%
- maxDailyLoss: 0.02, // 2%
- maxLeverage: 5, // 5x
- stopLossThreshold: 0.02, // 2%
- maxSlippage: 0.0005, // 0.05%
- minMarginRatio: 0.2 // 20%
- },
- moderate: {
- maxPositionSize: 0.1, // 10%
- maxDailyLoss: 0.05, // 5%
- maxLeverage: 10, // 10x
- stopLossThreshold: 0.05, // 5%
- maxSlippage: 0.001, // 0.1%
- minMarginRatio: 0.15 // 15%
- },
- aggressive: {
- maxPositionSize: 0.2, // 20%
- maxDailyLoss: 0.1, // 10%
- maxLeverage: 20, // 20x
- stopLossThreshold: 0.1, // 10%
- maxSlippage: 0.002, // 0.2%
- minMarginRatio: 0.1 // 10%
- }
- };
- return profiles[riskProfile];
- }
- /**
- * 批量生成账户
- */
- generateMultipleAccounts(
- count: number,
- baseName: string = 'HedgeAccount',
- initialUSDC: number = 10000,
- riskProfile: 'conservative' | 'moderate' | 'aggressive' = 'moderate'
- ): AccountConfig[] {
- const accounts: AccountConfig[] = [];
-
- for (let i = 1; i <= count; i++) {
- const accountName = `${baseName}${i}`;
- const account = this.generateAccountConfig(accountName, initialUSDC, riskProfile);
- accounts.push(account);
- }
-
- return accounts;
- }
- /**
- * 保存账户配置到文件
- */
- async saveAccountsToFile(accounts: AccountConfig[], encrypt: boolean = false): Promise<void> {
- // 确保配置目录存在
- await fs.mkdir(this.configDir, { recursive: true });
-
- let accountsToSave = accounts;
-
- if (encrypt) {
- // 在实际应用中,密码应该从环境变量或安全输入获取
- const password = process.env.ENCRYPTION_PASSWORD || 'default-password-change-in-production';
-
- accountsToSave = accounts.map(account => ({
- ...account,
- privateKey: EncryptionUtils.encryptPrivateKey(account.privateKey, password)
- }));
- }
-
- await fs.writeFile(
- this.accountsFile,
- JSON.stringify(accountsToSave, null, 2),
- 'utf-8'
- );
-
- console.log(`✅ 已保存 ${accounts.length} 个账户配置到 ${this.accountsFile}`);
- }
- /**
- * 从文件加载账户配置
- */
- async loadAccountsFromFile(decrypt: boolean = false): Promise<AccountConfig[]> {
- try {
- const data = await fs.readFile(this.accountsFile, 'utf-8');
- const accounts: AccountConfig[] = JSON.parse(data);
-
- if (decrypt) {
- const password = process.env.ENCRYPTION_PASSWORD || 'default-password-change-in-production';
-
- return accounts.map(account => ({
- ...account,
- privateKey: EncryptionUtils.decryptPrivateKey(account.privateKey, password)
- }));
- }
-
- return accounts;
- } catch (error) {
- console.error('❌ 加载账户配置失败:', error);
- return [];
- }
- }
- /**
- * 验证账户配置
- */
- validateAccountConfig(account: AccountConfig): { isValid: boolean; errors: string[] } {
- const errors: string[] = [];
-
- // 验证账户名称
- if (!account.name || account.name.length < 3 || account.name.length > 30) {
- errors.push('账户名称必须在3-30个字符之间');
- }
-
- // 验证私钥格式
- if (!account.privateKey || !account.privateKey.startsWith('0x') || account.privateKey.length !== 66) {
- errors.push('私钥格式无效');
- }
-
- // 验证初始USDC余额
- if (account.initialUSDC <= 0) {
- errors.push('初始USDC余额必须大于0');
- }
-
- // 验证风险限制
- const { riskLimits } = account;
- if (riskLimits.maxPositionSize <= 0 || riskLimits.maxPositionSize > 1) {
- errors.push('最大持仓大小必须在0-1之间');
- }
-
- if (riskLimits.maxDailyLoss <= 0 || riskLimits.maxDailyLoss > 1) {
- errors.push('最大日损失必须在0-1之间');
- }
-
- if (riskLimits.maxLeverage < 1) {
- errors.push('最大杠杆必须大于等于1');
- }
-
- if (riskLimits.stopLossThreshold <= 0 || riskLimits.stopLossThreshold > 1) {
- errors.push('止损阈值必须在0-1之间');
- }
-
- if (riskLimits.maxSlippage < 0) {
- errors.push('最大滑点不能为负数');
- }
-
- if (riskLimits.minMarginRatio <= 0 || riskLimits.minMarginRatio > 1) {
- errors.push('最小保证金比率必须在0-1之间');
- }
-
- return {
- isValid: errors.length === 0,
- errors
- };
- }
- /**
- * 显示账户信息
- */
- displayAccountInfo(account: AccountConfig, showPrivateKey: boolean = false): void {
- console.log('\n📋 账户信息:');
- console.log(` 名称: ${account.name}`);
- console.log(` 地址: ${ethers.computeAddress(account.privateKey)}`);
- console.log(` 初始USDC: ${account.initialUSDC.toLocaleString()}`);
-
- if (showPrivateKey) {
- console.log(` 私钥: ${account.privateKey}`);
- } else {
- console.log(` 私钥: ${account.privateKey.substring(0, 10)}...${account.privateKey.substring(62)}`);
- }
-
- console.log(' 风险限制:');
- console.log(` 最大持仓大小: ${(account.riskLimits.maxPositionSize * 100).toFixed(1)}%`);
- console.log(` 最大日损失: ${(account.riskLimits.maxDailyLoss * 100).toFixed(1)}%`);
- console.log(` 最大杠杆: ${account.riskLimits.maxLeverage}x`);
- console.log(` 止损阈值: ${(account.riskLimits.stopLossThreshold * 100).toFixed(1)}%`);
- console.log(` 最大滑点: ${(account.riskLimits.maxSlippage * 100).toFixed(3)}%`);
- console.log(` 最小保证金比率: ${(account.riskLimits.minMarginRatio * 100).toFixed(1)}%`);
- }
- }
- // 示例使用函数
- async function runAccountGenerationExample() {
- console.log('🚀 Pacifica 账户生成示例\n');
-
- const generator = new AccountGenerator();
-
- // 示例1: 生成单个账户
- console.log('📝 示例1: 生成单个账户');
- const singleAccount = generator.generateAccountConfig(
- 'TestAccount1',
- 10000,
- 'moderate'
- );
-
- const validation = generator.validateAccountConfig(singleAccount);
- if (validation.isValid) {
- generator.displayAccountInfo(singleAccount);
- } else {
- console.log('❌ 账户配置验证失败:', validation.errors);
- }
-
- // 示例2: 批量生成账户
- console.log('\n📝 示例2: 批量生成5个账户');
- const multipleAccounts = generator.generateMultipleAccounts(
- 5,
- 'HedgeAccount',
- 10000,
- 'moderate'
- );
-
- console.log(`✅ 生成了 ${multipleAccounts.length} 个账户`);
- multipleAccounts.forEach((account, index) => {
- console.log(` ${index + 1}. ${account.name} - ${ethers.computeAddress(account.privateKey)}`);
- });
-
- // 示例3: 保存和加载账户配置
- console.log('\n📝 示例3: 保存和加载账户配置');
- await generator.saveAccountsToFile(multipleAccounts, false);
-
- const loadedAccounts = await generator.loadAccountsFromFile(false);
- console.log(`✅ 从文件加载了 ${loadedAccounts.length} 个账户`);
-
- // 示例4: 不同风险配置的账户
- console.log('\n📝 示例4: 不同风险配置的账户');
- const conservativeAccount = generator.generateAccountConfig('ConservativeAccount', 10000, 'conservative');
- const aggressiveAccount = generator.generateAccountConfig('AggressiveAccount', 10000, 'aggressive');
-
- console.log('保守型账户:');
- generator.displayAccountInfo(conservativeAccount);
-
- console.log('\n激进型账户:');
- generator.displayAccountInfo(aggressiveAccount);
-
- // 示例5: 创建对冲账户组合
- console.log('\n📝 示例5: 创建对冲账户组合');
- const hedgingAccounts = [
- generator.generateAccountConfig('HedgeLong1', 10000, 'moderate'),
- generator.generateAccountConfig('HedgeShort1', 10000, 'moderate'),
- generator.generateAccountConfig('HedgeLong2', 10000, 'moderate'),
- generator.generateAccountConfig('HedgeShort2', 10000, 'moderate'),
- ];
-
- await generator.saveAccountsToFile(hedgingAccounts, false);
- console.log('✅ 对冲账户组合已保存');
-
- // 显示账户组合信息
- console.log('\n📊 对冲账户组合:');
- hedgingAccounts.forEach((account, index) => {
- const address = ethers.computeAddress(account.privateKey);
- const side = account.name.includes('Long') ? '多头' : '空头';
- console.log(` ${index + 1}. ${account.name} (${side}) - ${address}`);
- });
-
- console.log('\n🎉 账户生成示例完成!');
- console.log('\n💡 下一步:');
- console.log(' 1. 将生成的账户配置导入到Pacifica DEX');
- console.log(' 2. 为每个账户充值USDC');
- console.log(' 3. 启动对冲交易系统');
- console.log(' 4. 监控账户状态和风险指标');
- }
- // 命令行参数处理
- async function main() {
- const args = process.argv.slice(2);
-
- if (args.length === 0) {
- // 运行完整示例
- await runAccountGenerationExample();
- } else if (args[0] === 'generate') {
- // 生成指定数量的账户
- const count = parseInt(args[1]) || 5;
- const baseName = args[2] || 'HedgeAccount';
- const riskProfile = (args[3] as 'conservative' | 'moderate' | 'aggressive') || 'moderate';
-
- const generator = new AccountGenerator();
- const accounts = generator.generateMultipleAccounts(count, baseName, 10000, riskProfile);
-
- await generator.saveAccountsToFile(accounts, false);
-
- console.log(`✅ 已生成并保存 ${count} 个账户`);
- accounts.forEach((account, index) => {
- console.log(` ${index + 1}. ${account.name} - ${ethers.computeAddress(account.privateKey)}`);
- });
- } else if (args[0] === 'validate') {
- // 验证现有账户配置
- const generator = new AccountGenerator();
- const accounts = await generator.loadAccountsFromFile(false);
-
- console.log(`📋 验证 ${accounts.length} 个账户配置:`);
- accounts.forEach((account, index) => {
- const validation = generator.validateAccountConfig(account);
- const status = validation.isValid ? '✅' : '❌';
- console.log(` ${index + 1}. ${status} ${account.name}`);
- if (!validation.isValid) {
- validation.errors.forEach(error => console.log(` - ${error}`));
- }
- });
- } else {
- console.log('使用方法:');
- console.log(' tsx examples/account-generation.ts # 运行完整示例');
- console.log(' tsx examples/account-generation.ts generate [count] [name] [risk] # 生成账户');
- console.log(' tsx examples/account-generation.ts validate # 验证账户配置');
- }
- }
- // 运行主函数
- if (import.meta.url === `file://${process.argv[1]}`) {
- main().catch(console.error);
- }
- export { AccountGenerator, EncryptionUtils, AccountConfig };
|