# 5. 更多

### 多链支持

#### 概述

Ju.com 钱包当前支持三条主流公链：JuChain、Ethereum和BNB Smart Chain。每条链都有其独特的特性和优势，开发者需要根据具体需求选择合适的链进行部署。

#### 支持的区块链网络

```javascript
// 当前支持的主网配置
const MAINNET_CONFIGS = {
    // JuChain - 高性能、低费用的原生链
    JuChain: {
        chainId: '0x8956',  // 35158
        name: 'JuChain Mainnet',
        currency: {
            name: 'JU',
            symbol: 'JU',
            decimals: 18
        },
        rpc: 'https://rpc.juchain.com',
        explorer: 'https://explorer.juchain.com',
        features: {
            avgBlockTime: 3,  // 秒
            tps: 5000,        // 每秒交易数
            avgGasPrice: '5', // Gwei
            eip1559: true,
            supportedTokens: ['JRC20', 'JRC721', 'JRC1155']
        }
    },
    
    // Ethereum - 最大的智能合约平台
    Ethereum: {
        chainId: '0x1',  // 1
        name: 'Ethereum Mainnet',
        currency: {
            name: 'Ether',
            symbol: 'ETH',
            decimals: 18
        },
        rpc: 'https://mainnet.infura.io/v3/YOUR-PROJECT-ID',
        explorer: 'https://etherscan.io',
        features: {
            avgBlockTime: 12,
            tps: 15,
            avgGasPrice: '30',
            eip1559: true,
            supportedTokens: ['ERC20', 'ERC721', 'ERC1155']
        }
    },
    
    // BNB Smart Chain - 高性能、低费用
    BSC: {
        chainId: '0x38',  // 56
        name: 'BNB Smart Chain',
        currency: {
            name: 'BNB',
            symbol: 'BNB',
            decimals: 18
        },
        rpc: 'https://bsc-dataseed.binance.org',
        explorer: 'https://bscscan.com',
        features: {
            avgBlockTime: 3,
            tps: 160,
            avgGasPrice: '5',
            eip1559: false,
            supportedTokens: ['BEP20', 'BEP721', 'BEP1155']
        }
    }
};
```

#### 多链DApp开发

**1. 统一的多链接口**

```javascript
// 多链管理器
class MultiChainManager {
    constructor(provider) {
        this.provider = provider;
        this.chains = MAINNET_CONFIGS;
        this.currentChain = null;
    }
    
    // 初始化，获取当前链
    async init() {
        const chainId = await this.provider.request({
            method: 'eth_chainId'
        });
        this.currentChain = this.getChainByHexId(chainId);
        return this.currentChain;
    }
    
    // 根据16进制ID获取链配置
    getChainByHexId(hexId) {
        return Object.values(this.chains).find(
            chain => chain.chainId === hexId
        );
    }
    
    // 根据10进制ID获取链配置
    getChainById(id) {
        const hexId = '0x' + id.toString(16);
        return this.getChainByHexId(hexId);
    }
    
    // 切换链
    async switchChain(chainId) {
        try {
            await this.provider.request({
                method: 'wallet_switchEthereumChain',
                params: [{ chainId }]
            });
            this.currentChain = this.getChainByHexId(chainId);
            return true;
        } catch (error) {
            if (error.code === 4902) {
                // 链未添加，尝试添加
                const chain = this.getChainByHexId(chainId);
                if (chain) {
                    return await this.addChain(chain);
                }
            }
            throw error;
        }
    }
    
    // 添加链
    async addChain(chainConfig) {
        const params = {
            chainId: chainConfig.chainId,
            chainName: chainConfig.name,
            nativeCurrency: chainConfig.currency,
            rpcUrls: [chainConfig.rpc],
            blockExplorerUrls: [chainConfig.explorer]
        };
        
        await this.provider.request({
            method: 'wallet_addEthereumChain',
            params: [params]
        });
        
        return true;
    }
    
    // 获取链特定的合约地址
    getContractAddress(contractName) {
        const contracts = {
            JuChain: {
                USDT: '0x...',
                WETH: '0x...',
                DEX: '0x...',
                Bridge: '0x...'
            },
            Ethereum: {
                USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
                USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
                WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
                Uniswap: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'
            },
            BSC: {
                USDT: '0x55d398326f99059fF775485246999027B3197955',
                BUSD: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',
                WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
                PancakeSwap: '0x10ED43C718714eb63d5aA57B78B54704E256024E'
            }
        };
        
        return contracts[this.currentChain.name]?.[contractName];
    }
}
```

**2. 跨链交互示例**

```javascript
// 跨链桥接示例
class CrossChainBridge {
    constructor(provider) {
        this.provider = provider;
        this.chainManager = new MultiChainManager(provider);
    }
    
    // 跨链转账
    async bridgeTokens(params) {
        const {
            fromChain,
            toChain,
            token,
            amount,
            recipient
        } = params;
        
        // 1. 切换到源链
        await this.chainManager.switchChain(fromChain);
        
        // 2. 检查余额
        const balance = await this.getTokenBalance(token);
        if (balance < amount) {
            throw new Error('余额不足');
        }
        
        // 3. 授权桥接合约
        const bridgeAddress = this.chainManager.getContractAddress('Bridge');
        await this.approveToken(token, bridgeAddress, amount);
        
        // 4. 发起跨链交易
        const tx = await this.provider.request({
            method: 'eth_sendTransaction',
            params: [{
                from: await this.getAccount(),
                to: bridgeAddress,
                data: this.encodeBridgeCall(toChain, token, amount, recipient)
            }]
        });
        
        // 5. 等待确认
        const receipt = await this.waitForTransaction(tx);
        
        return {
            txHash: tx,
            receipt: receipt,
            bridgeId: this.extractBridgeId(receipt)
        };
    }
    
    // 监听跨链状态
    async monitorBridgeStatus(bridgeId, targetChain) {
        // 切换到目标链
        await this.chainManager.switchChain(targetChain);
        
        // 轮询检查状态
        let attempts = 0;
        while (attempts < 100) {
            const status = await this.checkBridgeStatus(bridgeId);
            
            if (status === 'completed') {
                return true;
            } else if (status === 'failed') {
                throw new Error('跨链失败');
            }
            
            // 等待30秒再次检查
            await new Promise(resolve => setTimeout(resolve, 30000));
            attempts++;
        }
        
        throw new Error('跨链超时');
    }
}
```

**3. 多链数据聚合**

```javascript
// 多链资产管理
class MultiChainAssetManager {
    constructor(provider) {
        this.provider = provider;
        this.chains = ['0x1', '0x38', '0x8956'];
    }
    
    // 获取所有链的资产
    async getAllAssets(address) {
        const assets = {};
        
        for (const chainId of this.chains) {
            try {
                // 切换到对应链
                await this.provider.request({
                    method: 'wallet_switchEthereumChain',
                    params: [{ chainId }]
                });
                
                // 获取原生币余额
                const balance = await this.provider.request({
                    method: 'eth_getBalance',
                    params: [address, 'latest']
                });
                
                // 获取代币余额
                const tokens = await this.provider.request({
                    method: 'jucoin_getTokenBalances',
                    params: [{ account: address, chainId }]
                });
                
                assets[chainId] = {
                    native: balance,
                    tokens: tokens
                };
            } catch (error) {
                console.error(`获取链${chainId}资产失败:`, error);
                assets[chainId] = { error: error.message };
            }
        }
        
        return assets;
    }
    
    // 计算总价值（USD）
    async calculateTotalValue(assets) {
        const prices = await this.fetchTokenPrices();
        let totalValue = 0;
        
        for (const [chainId, chainAssets] of Object.entries(assets)) {
            if (chainAssets.error) continue;
            
            // 计算原生币价值
            const chain = this.getChainInfo(chainId);
            const nativeAmount = parseInt(chainAssets.native, 16) / 1e18;
            totalValue += nativeAmount * prices[chain.currency.symbol];
            
            // 计算代币价值
            for (const token of chainAssets.tokens) {
                const tokenAmount = parseInt(token.balance) / Math.pow(10, token.decimals);
                totalValue += tokenAmount * (prices[token.symbol] || 0);
            }
        }
        
        return totalValue;
    }
}
```

### 安全审计

#### 智能合约安全检查清单

```javascript
// 合约安全检查器
class ContractSecurityChecker {
    constructor(provider) {
        this.provider = provider;
    }
    
    // 检查合约安全性
    async checkContractSecurity(contractAddress) {
        const checks = {
            isContract: await this.isContract(contractAddress),
            isVerified: await this.isVerified(contractAddress),
            hasProxyPattern: await this.checkProxyPattern(contractAddress),
            hasOwnership: await this.checkOwnership(contractAddress),
            hasPausable: await this.checkPausable(contractAddress),
            hasReentrancyGuard: await this.checkReentrancyGuard(contractAddress),
            hasIntegerOverflow: await this.checkIntegerOverflow(contractAddress),
            hasAccessControl: await this.checkAccessControl(contractAddress)
        };
        
        const score = this.calculateSecurityScore(checks);
        
        return {
            address: contractAddress,
            checks: checks,
            score: score,
            risk: this.getRiskLevel(score)
        };
    }
    
    // 检查是否是合约
    async isContract(address) {
        const code = await this.provider.request({
            method: 'eth_getCode',
            params: [address, 'latest']
        });
        return code !== '0x';
    }
    
    // 检查是否已验证
    async isVerified(address) {
        // 调用区块浏览器API检查
        // 这里以Etherscan为例
        const response = await fetch(
            `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`
        );
        const data = await response.json();
        return data.status === '1';
    }
    
    // 检查代理模式
    async checkProxyPattern(address) {
        const code = await this.provider.request({
            method: 'eth_getCode',
            params: [address, 'latest']
        });
        
        // 检查常见的代理模式特征
        const proxyPatterns = [
            '363d3d373d3d3d363d73',  // EIP-1167 Minimal Proxy
            'push1 0x00 dup1 revert',  // Proxy fallback
            'delegatecall'             // Delegate call pattern
        ];
        
        return proxyPatterns.some(pattern => 
            code.toLowerCase().includes(pattern.toLowerCase())
        );
    }
    
    // 计算安全分数
    calculateSecurityScore(checks) {
        const weights = {
            isContract: 10,
            isVerified: 30,
            hasProxyPattern: -10,
            hasOwnership: 10,
            hasPausable: 10,
            hasReentrancyGuard: 15,
            hasIntegerOverflow: -20,
            hasAccessControl: 15
        };
        
        let score = 0;
        for (const [check, value] of Object.entries(checks)) {
            if (value) score += weights[check] || 0;
        }
        
        return Math.max(0, Math.min(100, score));
    }
    
    // 获取风险级别
    getRiskLevel(score) {
        if (score >= 80) return 'LOW';
        if (score >= 60) return 'MEDIUM';
        if (score >= 40) return 'HIGH';
        return 'CRITICAL';
    }
}
```

#### 交易安全验证

```javascript
// 交易安全验证器
class TransactionValidator {
    constructor(provider) {
        this.provider = provider;
        this.knownContracts = new Map();
        this.loadKnownContracts();
    }
    
    // 加载已知合约
    loadKnownContracts() {
        // 加载已知的安全合约
        this.knownContracts.set(
            '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
            { name: 'Uniswap V2 Router', safe
             true }
);
this.knownContracts.set(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
{ name: 'USDC', safe: true }
);
// 加载更多已知合约...
}

```

```
// 验证交易安全性
async validateTransaction(tx) {
    const validations = {
        // 基础检查
        hasValidAddress: this.isValidAddress(tx.to),
        hasReasonableGas: await this.checkGasLimit(tx),
        hasReasonableValue: this.checkValue(tx),
        
        // 合约检查
        isKnownContract: this.knownContracts.has(tx.to),
        contractRisk: await this.assessContractRisk(tx.to),
        
        // 函数调用检查
        functionRisk: await this.analyzeFunctionCall(tx),
        
        // 模拟执行
        simulationResult: await this.simulateTransaction(tx),
        
        // 异常模式检查
        hasAnomalousPattern: await this.checkAnomalousPattern(tx)
    };
    
    const riskScore = this.calculateRiskScore(validations);
    const warnings = this.generateWarnings(validations);
    
    return {
        validations,
        riskScore,
        riskLevel: this.getRiskLevel(riskScore),
        warnings,
        recommendation: this.getRecommendation(riskScore, warnings)
    };
}

// 分析函数调用
async analyzeFunctionCall(tx) {
    if (!tx.data || tx.data === '0x') {
        return { type: 'transfer', risk: 'LOW' };
    }
    
    const selector = tx.data.slice(0, 10);
    const dangerousFunctions = {
        '0x095ea7b3': { name: 'approve', risk: 'MEDIUM' },
        '0xa22cb465': { name: 'setApprovalForAll', risk: 'HIGH' },
        '0x23b872dd': { name: 'transferFrom', risk: 'MEDIUM' },
        '0x39509351': { name: 'increaseAllowance', risk: 'MEDIUM' },
        '0xf2fde38b': { name: 'transferOwnership', risk: 'CRITICAL' }
    };
    
    const funcInfo = dangerousFunctions[selector];
    if (funcInfo) {
        return {
            type: 'dangerous',
            function: funcInfo.name,
            risk: funcInfo.risk
        };
    }
    
    return { type: 'unknown', risk: 'MEDIUM' };
}

// 检查异常模式
async checkAnomalousPattern(tx) {
    const patterns = [];
    
    // 检查是否给新创建的合约发送大额资金
    if (tx.value && parseInt(tx.value, 16) > 1e18) {
        const age = await this.getContractAge(tx.to);
        if (age < 86400) { // 少于1天
            patterns.push('SENDING_TO_NEW_CONTRACT');
        }
    }
    
    // 检查是否批准了无限额度
    if (tx.data?.startsWith('0x095ea7b3')) {
        const amount = '0x' + tx.data.slice(74);
        if (amount === '0x' + 'f'.repeat(64)) {
            patterns.push('UNLIMITED_APPROVAL');
        }
    }
    
    // 检查是否调用了自毁函数
    if (tx.data?.includes('ff') && tx.data.length === 10) {
        patterns.push('SELFDESTRUCT_CALL');
    }
    
    return patterns;
}

// 生成警告信息
generateWarnings(validations) {
    const warnings = [];
    
    if (!validations.isKnownContract) {
        warnings.push({
            level: 'WARNING',
            message: '正在与未知合约交互，请谨慎操作'
        });
    }
    
    if (validations.functionRisk?.risk === 'HIGH' || 
        validations.functionRisk?.risk === 'CRITICAL') {
        warnings.push({
            level: 'DANGER',
            message: `正在执行高风险操作: ${validations.functionRisk.function}`
        });
    }
    
    if (validations.hasAnomalousPattern?.includes('UNLIMITED_APPROVAL')) {
        warnings.push({
            level: 'DANGER',
            message: '检测到无限额度授权，建议设置具体数量'
        });
    }
    
    if (validations.simulationResult?.error) {
        warnings.push({
            level: 'DANGER',
            message: '交易模拟失败: ' + validations.simulationResult.error
        });
    }
    
    return warnings;
}
```

#### 私钥安全管理

```javascript
// 私钥安全管理最佳实践
class PrivateKeySecurityManager {
    // 永远不要在代码中硬编码私钥
    static NEVER_DO_THIS = {
        privateKey: '0x...', // 绝对不要这样做！
        mnemonic: 'word1 word2 ...' // 绝对不要这样做！
    };
    
    // 安全的私钥管理方式
    static secureKeyManagement() {
        // 1. 使用硬件钱包
        const hardwareWallet = {
            type: 'Ledger/Trezor',
            benefits: [
                '私钥永不离开设备',
                '交易需要物理确认',
                '防止恶意软件攻击'
            ]
        };
        
        // 2. 使用加密存储
        const encryptedStorage = {
            method: 'AES-256-GCM',
            keyDerivation: 'PBKDF2',
            iterations: 100000,
            storage: 'SecureEnclave/KeyStore'
        };
        
        // 3. 使用环境变量（仅用于开发）
        const envVariables = {
            development: process.env.DEV_PRIVATE_KEY,
            production: 'USE_HARDWARE_WALLET'
        };
        
        // 4. 使用密钥管理服务
        const keyManagementService = {
            providers: ['AWS KMS', 'HashiCorp Vault', 'Azure Key Vault'],
            benefits: [
                '集中式密钥管理',
                '访问控制和审计',
                '密钥轮换'
            ]
        };
    }
    
    // 安全签名实践
    static async secureSign(provider, message) {
        // 1. 验证消息内容
        const messageValidation = {
            isHex: message.startsWith('0x'),
            length: message.length,
            content: this.parseMessage(message)
        };
        
        // 2. 显示用户友好的消息
        const userMessage = this.formatForUser(messageValidation.content);
        
        // 3. 请求用户确认
        const userConfirmed = await this.requestUserConfirmation({
            action: 'SIGN_MESSAGE',
            message: userMessage,
            details: messageValidation
        });
        
        if (!userConfirmed) {
            throw new Error('用户取消签名');
        }
        
        // 4. 执行签名
        const signature = await provider.request({
            method: 'personal_sign',
            params: [message, provider.selectedAddress]
        });
        
        // 5. 验证签名
        const isValid = await this.verifySignature(
            message,
            signature,
            provider.selectedAddress
        );
        
        if (!isValid) {
            throw new Error('签名验证失败');
        }
        
        return signature;
    }
}
Gas优化
Gas估算和优化策略
// Gas优化管理器
class GasOptimizer {
    constructor(provider) {
        this.provider = provider;
        this.gasHistory = new Map();
        this.gasPriceCache = new Map();
    }
    
    // 智能Gas估算
    async estimateOptimalGas(tx) {
        // 1. 基础Gas估算
        const baseEstimate = await this.provider.request({
            method: 'eth_estimateGas',
            params: [tx]
        });
        
        // 2. 添加安全边际（10-20%）
        const safetyMargin = 1.15;
        const gasLimit = Math.ceil(parseInt(baseEstimate, 16) * safetyMargin);
        
        // 3. 获取优化的Gas价格
        const gasPrice = await this.getOptimalGasPrice(tx);
        
        // 4. 计算总成本
        const totalCost = gasLimit * gasPrice.standard;
        
        return {
            gasLimit: '0x' + gasLimit.toString(16),
            gasPrice: gasPrice,
            estimatedCost: totalCost,
            estimatedTime: this.estimateConfirmationTime(gasPrice.standard)
        };
    }
    
    // 获取优化的Gas价格
    async getOptimalGasPrice(tx) {
        const chainId = await this.provider.request({
            method: 'eth_chainId'
        });
        
        // 检查缓存
        const cacheKey = `${chainId}-${Date.now() / 60000 | 0}`; // 1分钟缓存
        if (this.gasPriceCache.has(cacheKey)) {
            return this.gasPriceCache.get(cacheKey);
        }
        
        // 获取链特定的Gas价格
        let gasPrice;
        switch (chainId) {
            case '0x1': // Ethereum
                gasPrice = await this.getEthereumGasPrice();
                break;
            case '0x38': // BSC
                gasPrice = await this.getBSCGasPrice();
                break;
            case '0x8956': // JuChain
                gasPrice = await this.getJuChainGasPrice();
                break;
            default:
                gasPrice = await this.getDefaultGasPrice();
        }
        
        // 缓存结果
        this.gasPriceCache.set(cacheKey, gasPrice);
        
        return gasPrice;
    }
    
    // Ethereum EIP-1559 Gas价格
    async getEthereumGasPrice() {
        const block = await this.provider.request({
            method: 'eth_getBlockByNumber',
            params: ['latest', false]
        });
        
        const baseFee = parseInt(block.baseFeePerGas, 16);
        
        // 获取历史优先费
        const feeHistory = await this.provider.request({
            method: 'eth_feeHistory',
            params: [10, 'latest', [25, 50, 75]]
        });
        
        const priorityFees = feeHistory.reward
            .map(r => parseInt(r[1], 16)) // 使用50百分位
            .filter(f => f > 0);
        
        const avgPriorityFee = priorityFees.length > 0
            ? priorityFees.reduce((a, b) => a + b) / priorityFees.length
            : 1e9; // 1 Gwei默认值
        
        return {
            slow: {
                maxFeePerGas: '0x' + (baseFee + avgPriorityFee * 0.8).toString(16),
                maxPriorityFeePerGas: '0x' + (avgPriorityFee * 0.8).toString(16)
            },
            standard: {
                maxFeePerGas: '0x' + (baseFee + avgPriorityFee).toString(16),
                maxPriorityFeePerGas: '0x' + avgPriorityFee.toString(16)
            },
            fast: {
                maxFeePerGas: '0x' + (baseFee + avgPriorityFee * 1.5).toString(16),
                maxPriorityFeePerGas: '0x' + (avgPriorityFee * 1.5).toString(16)
            }
        };
    }
    
    // 批量交易优化
    async optimizeBatchTransactions(transactions) {
        // 1. 分析交易依赖关系
        const dependencies = this.analyzeDependencies(transactions);
        
        // 2. 优化交易顺序
        const optimizedOrder = this.topologicalSort(transactions, dependencies);
        
        // 3. 合并可合并的交易
        const mergedTxs = await this.mergeTransactions(optimizedOrder);
        
        // 4. 使用多调用合约
        if (mergedTxs.length > 1) {
            const multicallTx = await this.createMulticallTransaction(mergedTxs);
            return [multicallTx];
        }
        
        return mergedTxs;
    }
    
    // 创建多调用交易
    async createMulticallTransaction(transactions) {
        const multicallAddress = this.getMulticallAddress();
        const calls = transactions.map(tx => ({
            target: tx.to,
            callData: tx.data
        }));
        
        const multicallData = this.encodeMulticall(calls);
        
        return {
            to: multicallAddress,
            data: multicallData,
            value: '0x0',
            gas: await this.estimateMulticallGas(calls)
        };
    }
    
    // Gas使用分析
    async analyzeGasUsage(txHash) {
        const receipt = await this.provider.request({
            method: 'eth_getTransactionReceipt',
            params: [txHash]
        });
        
        const tx = await this.provider.request({
            method: 'eth_getTransactionByHash',
            params: [txHash]
        });
        
        const gasUsed = parseInt(receipt.gasUsed, 16);
        const gasLimit = parseInt(tx.gas, 16);
        const gasPrice = parseInt(tx.gasPrice || tx.maxFeePerGas, 16);
        
        const analysis = {
            gasUsed,
            gasLimit,
            gasEfficiency: (gasUsed / gasLimit * 100).toFixed(2) + '%',
            gasWasted: gasLimit - gasUsed,
            actualCost: gasUsed * gasPrice / 1e18,
            potentialSaving: (gasLimit - gasUsed) * gasPrice / 1e18,
            recommendation: this.getGasRecommendation(gasUsed, gasLimit)
        };
        
        // 存储历史记录用于未来优化
        this.gasHistory.set(tx.to, {
            ...analysis,
            timestamp: Date.now()
        });
        
        return analysis;
    }
}
合约调用优化
// 智能合约调用优化器
class ContractCallOptimizer {
    constructor(provider) {
        this.provider = provider;
        this.callDataCache = new Map();
    }
    
    // 优化合约调用
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jucoin-wallet.gitbook.io/jucoin-wallet-docs/5.-geng-duo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
