# 5. More

## Multi-chain Support

#### Overview

Ju.com Wallet currently supports three mainstream public chains: JuChain, Ethereum, and BNB Smart Chain. Each chain has its unique characteristics and advantages, and developers need to choose the appropriate chain for deployment based on specific requirements.

#### Supported Blockchain Networks

```javascript
// Currently supported mainnet configurations
const MAINNET_CONFIGS = {
    // JuChain - High-performance, low-fee native chain
    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,  // seconds
            tps: 5000,        // transactions per second
            avgGasPrice: '5', // Gwei
            eip1559: true,
            supportedTokens: ['JRC20', 'JRC721', 'JRC1155']
        }
    },
    
    // Ethereum - The largest smart contract platform
    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 - High performance, low fees
    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']
        }
    }
};
```

#### Multi-chain DApp Development

**1. Unified Multi-chain Interface**

```javascript
// Multi-chain manager
class MultiChainManager {
    constructor(provider) {
        this.provider = provider;
        this.chains = MAINNET_CONFIGS;
        this.currentChain = null;
    }
    
    // Initialize and get current chain
    async init() {
        const chainId = await this.provider.request({
            method: 'eth_chainId'
        });
        this.currentChain = this.getChainByHexId(chainId);
        return this.currentChain;
    }
    
    // Get chain config by hex ID
    getChainByHexId(hexId) {
        return Object.values(this.chains).find(
            chain => chain.chainId === hexId
        );
    }
    
    // Get chain config by decimal ID
    getChainById(id) {
        const hexId = '0x' + id.toString(16);
        return this.getChainByHexId(hexId);
    }
    
    // Switch chain
    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) {
                // Chain not added, try to add it
                const chain = this.getChainByHexId(chainId);
                if (chain) {
                    return await this.addChain(chain);
                }
            }
            throw error;
        }
    }
    
    // Add chain
    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;
    }
    
    // Get chain-specific contract addresses
    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. Cross-chain Interaction Example**

```javascript
// Cross-chain bridge example
class CrossChainBridge {
    constructor(provider) {
        this.provider = provider;
        this.chainManager = new MultiChainManager(provider);
    }
    
    // Cross-chain transfer
    async bridgeTokens(params) {
        const {
            fromChain,
            toChain,
            token,
            amount,
            recipient
        } = params;
        
        // 1. Switch to source chain
        await this.chainManager.switchChain(fromChain);
        
        // 2. Check balance
        const balance = await this.getTokenBalance(token);
        if (balance < amount) {
            throw new Error('Insufficient balance');
        }
        
        // 3. Approve bridge contract
        const bridgeAddress = this.chainManager.getContractAddress('Bridge');
        await this.approveToken(token, bridgeAddress, amount);
        
        // 4. Initiate cross-chain transaction
        const tx = await this.provider.request({
            method: 'eth_sendTransaction',
            params: [{
                from: await this.getAccount(),
                to: bridgeAddress,
                data: this.encodeBridgeCall(toChain, token, amount, recipient)
            }]
        });
        
        // 5. Wait for confirmation
        const receipt = await this.waitForTransaction(tx);
        
        return {
            txHash: tx,
            receipt: receipt,
            bridgeId: this.extractBridgeId(receipt)
        };
    }
    
    // Monitor cross-chain status
    async monitorBridgeStatus(bridgeId, targetChain) {
        // Switch to target chain
        await this.chainManager.switchChain(targetChain);
        
        // Poll for status
        let attempts = 0;
        while (attempts < 100) {
            const status = await this.checkBridgeStatus(bridgeId);
            
            if (status === 'completed') {
                return true;
            } else if (status === 'failed') {
                throw new Error('Cross-chain failed');
            }
            
            // Wait 30 seconds before checking again
            await new Promise(resolve => setTimeout(resolve, 30000));
            attempts++;
        }
        
        throw new Error('Cross-chain timeout');
    }
}
```

**3. Multi-chain Data Aggregation**

```javascript
// Multi-chain asset management
class MultiChainAssetManager {
    constructor(provider) {
        this.provider = provider;
        this.chains = ['0x1', '0x38', '0x8956'];
    }
    
    // Get assets from all chains
    async getAllAssets(address) {
        const assets = {};
        
        for (const chainId of this.chains) {
            try {
                // Switch to corresponding chain
                await this.provider.request({
                    method: 'wallet_switchEthereumChain',
                    params: [{ chainId }]
                });
                
                // Get native token balance
                const balance = await this.provider.request({
                    method: 'eth_getBalance',
                    params: [address, 'latest']
                });
                
                // Get token balances
                const tokens = await this.provider.request({
                    method: 'jucoin_getTokenBalances',
                    params: [{ account: address, chainId }]
                });
                
                assets[chainId] = {
                    native: balance,
                    tokens: tokens
                };
            } catch (error) {
                console.error(`Failed to get assets for chain ${chainId}:`, error);
                assets[chainId] = { error: error.message };
            }
        }
        
        return assets;
    }
    
    // Calculate total value (USD)
    async calculateTotalValue(assets) {
        const prices = await this.fetchTokenPrices();
        let totalValue = 0;
        
        for (const [chainId, chainAssets] of Object.entries(assets)) {
            if (chainAssets.error) continue;
            
            // Calculate native token value
            const chain = this.getChainInfo(chainId);
            const nativeAmount = parseInt(chainAssets.native, 16) / 1e18;
            totalValue += nativeAmount * prices[chain.currency.symbol];
            
            // Calculate token values
            for (const token of chainAssets.tokens) {
                const tokenAmount = parseInt(token.balance) / Math.pow(10, token.decimals);
                totalValue += tokenAmount * (prices[token.symbol] || 0);
            }
        }
        
        return totalValue;
    }
}
```

### Security Audit

#### Smart Contract Security Checklist

```javascript
// Contract security checker
class ContractSecurityChecker {
    constructor(provider) {
        this.provider = provider;
    }
    
    // Check contract security
    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)
        };
    }
    
    // Check if address is a contract
    async isContract(address) {
        const code = await this.provider.request({
            method: 'eth_getCode',
            params: [address, 'latest']
        });
        return code !== '0x';
    }
    
    // Check if contract is verified
    async isVerified(address) {
        // Call blockchain explorer API
        // Using Etherscan as example
        const response = await fetch(
            `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`
        );
        const data = await response.json();
        return data.status === '1';
    }
    
    // Check proxy pattern
    async checkProxyPattern(address) {
        const code = await this.provider.request({
            method: 'eth_getCode',
            params: [address, 'latest']
        });
        
        // Check common proxy pattern signatures
        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())
        );
    }
    
    // Calculate security score
    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));
    }
    
    // Get risk level
    getRiskLevel(score) {
        if (score >= 80) return 'LOW';
        if (score >= 60) return 'MEDIUM';
        if (score >= 40) return 'HIGH';
        return 'CRITICAL';
    }
}
```

#### Transaction Security Validation

```javascript
// Transaction security validator
class TransactionValidator {
    constructor(provider) {
        this.provider = provider;
        this.knownContracts = new Map();
        this.loadKnownContracts();
    }
    
    // Load known contracts
    loadKnownContracts() {
        // Load known safe contracts
        this.knownContracts.set(
            '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
            { name: 'Uniswap V2 Router', safe: true }
        );
        this.knownContracts.set(
            '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
            { name: 'USDC', safe: true }
        );
        // Load more known contracts...
    }
    
    // Validate transaction security
    async validateTransaction(tx) {
        const validations = {
            // Basic checks
            hasValidAddress: this.isValidAddress(tx.to),
            hasReasonableGas: await this.checkGasLimit(tx),
            hasReasonableValue: this.checkValue(tx),
            
            // Contract checks
            isKnownContract: this.knownContracts.has(tx.to),
            contractRisk: await this.assessContractRisk(tx.to),
            
            // Function call checks
            functionRisk: await this.analyzeFunctionCall(tx),
            
            // Simulation
            simulationResult: await this.simulateTransaction(tx),
            
            // Anomaly pattern checks
            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)
        };
    }
    
    // Analyze function call
    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' };
    }
    
    // Check anomalous patterns
    async checkAnomalousPattern(tx) {
        const patterns = [];
        
        // Check if sending large amount to newly created contract
        if (tx.value && parseInt(tx.value, 16) > 1e18) {
            const age = await this.getContractAge(tx.to);
            if (age < 86400) { // Less than 1 day
                patterns.push('SENDING_TO_NEW_CONTRACT');
            }
        }
        
        // Check for unlimited approval
        if (tx.data?.startsWith('0x095ea7b3')) {
            const amount = '0x' + tx.data.slice(74);
            if (amount === '0x' + 'f'.repeat(64)) {
                patterns.push('UNLIMITED_APPROVAL');
            }
        }
        
        // Check for selfdestruct call
        if (tx.data?.includes('ff') && tx.data.length === 10) {
            patterns.push('SELFDESTRUCT_CALL');
        }
        
        return patterns;
    }
    
    // Generate warnings
    generateWarnings(validations) {
        const warnings = [];
        
        if (!validations.isKnownContract) {
            warnings.push({
                level: 'WARNING',
                message: 'Interacting with unknown contract, please proceed with caution'
            });
        }
        
        if (validations.functionRisk?.risk === 'HIGH' || 
            validations.functionRisk?.risk === 'CRITICAL') {
            warnings.push({
                level: 'DANGER',
                message: `Executing high-risk operation: ${validations.functionRisk.function}`
            });
        }
        
        if (validations.hasAnomalousPattern?.includes('UNLIMITED_APPROVAL')) {
            warnings.push({
                level: 'DANGER',
                message: 'Unlimited approval detected, recommend setting specific amount'
            });
        }
        
        if (validations.simulationResult?.error) {
            warnings.push({
                level: 'DANGER',
                message: 'Transaction simulation failed: ' + validations.simulationResult.error
            });
        }
        
        return warnings;
    }
}
```

#### Private Key Security Management

```javascript
// Private key security management best practices
class PrivateKeySecurityManager {
    // Never hardcode private keys in code
    static NEVER_DO_THIS = {
        privateKey: '0x...', // Never do this!
        mnemonic: 'word1 word2 ...' // Never do this!
    };
    
    // Secure private key management methods
    static secureKeyManagement() {
        // 1. Use hardware wallets
        const hardwareWallet = {
            type: 'Ledger/Trezor',
            benefits: [
                'Private keys never leave device',
                'Transactions require physical confirmation',
                'Protection against malware attacks'
            ]
        };
        
        // 2. Use encrypted storage
        const encryptedStorage = {
            method: 'AES-256-GCM',
            keyDerivation: 'PBKDF2',
            iterations: 100000,
            storage: 'SecureEnclave/KeyStore'
        };
        
        // 3. Use environment variables (development only)
        const envVariables = {
            development: process.env.DEV_PRIVATE_KEY,
            production: 'USE_HARDWARE_WALLET'
        };
        
        // 4. Use key management services
        const keyManagementService = {
            providers: ['AWS KMS', 'HashiCorp Vault', 'Azure Key Vault'],
            benefits: [
                'Centralized key management',
                'Access control and auditing',
                'Key rotation'
            ]
        };
    }
    
    // Secure signing practices
    static async secureSign(provider, message) {
        // 1. Validate message content
        const messageValidation = {
            isHex: message.startsWith('0x'),
            length: message.length,
            content: this.parseMessage(message)
        };
        
        // 2. Display user-friendly message
        const userMessage = this.formatForUser(messageValidation.content);
        
        // 3. Request user confirmation
        const userConfirmed = await this.requestUserConfirmation({
            action: 'SIGN_MESSAGE',
            message: userMessage,
            details: messageValidation
        });
        
        if (!userConfirmed) {
            throw new Error('User cancelled signing');
        }
        
        // 4. Execute signing
        const signature = await provider.request({
            method: 'personal_sign',
            params: [message, provider.selectedAddress]
        });
        
        // 5. Verify signature
        const isValid = await this.verifySignature(
            message,
            signature,
            provider.selectedAddress
        );
        
        if (!isValid) {
            throw new Error('Signature verification failed');
        }
        
        return signature;
    }
}
```

### Gas Optimization

#### Gas Estimation and Optimization Strategies

```javascript
// Gas optimization manager
class GasOptimizer {
    constructor(provider) {
        this.provider = provider;
        this.gasHistory = new Map();
        this.gasPriceCache = new Map();
    }
    
    // Smart gas estimation
    async estimateOptimalGas(tx) {
        // 1. Basic gas estimation
        const baseEstimate = await this.provider.request({
            method: 'eth_estimateGas',
            params: [tx]
        });
        
        // 2. Add safety margin (10-20%)
        const safetyMargin = 1.15;
        const gasLimit = Math.ceil(parseInt(baseEstimate, 16) * safetyMargin);
        
        // 3. Get optimized gas price
        const gasPrice = await this.getOptimalGasPrice(tx);
        
        // 4. Calculate total cost
        const totalCost = gasLimit * gasPrice.standard;
        
        return {
            gasLimit: '0x' + gasLimit.toString(16),
            gasPrice: gasPrice,
            estimatedCost: totalCost,
            estimatedTime: this.estimateConfirmationTime(gasPrice.standard)
        };
    }
    
    // Get optimized gas price
    async getOptimalGasPrice(tx) {
        const chainId = await this.provider.request({
            method: 'eth_chainId'
        });
        
        // Check cache
        const cacheKey = `${chainId}-${Date.now() / 60000 | 0}`; // 1-minute cache
        if (this.gasPriceCache.has(cacheKey)) {
            return this.gasPriceCache.get(cacheKey);
        }
        
        // Get chain-specific gas price
        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();
        }
        
        // Cache result
        this.gasPriceCache.set(cacheKey, gasPrice);
        
        return gasPrice;
    }
    
    // Ethereum EIP-1559 gas price
    async getEthereumGasPrice() {
        const block = await this.provider.request({
            method: 'eth_getBlockByNumber',
            params: ['latest', false]
        });
        
        const baseFee = parseInt(block.baseFeePerGas, 16);
        
        // Get historical priority fees
        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)) // Use 50th percentile
            .filter(f => f > 0);
        
        const avgPriorityFee = priorityFees.length > 0
            ? priorityFees.reduce((a, b) => a + b) / priorityFees.length
            : 1e9; // 1 Gwei default
        
        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)
            }
        };
    }
    
    // Batch transaction optimization
    async optimizeBatchTransactions(transactions) {
        // 1. Analyze transaction dependencies
        const dependencies = this.analyzeDependencies(transactions);
        
        // 2. Optimize transaction order
        const optimizedOrder = this.topologicalSort(transactions, dependencies);
        
        // 3. Merge mergeable transactions
        const mergedTxs = await this.mergeTransactions(optimizedOrder);
        
        // 4. Use multicall contract
        if (mergedTxs.length > 1) {
            const multicallTx = await this.createMulticallTransaction(mergedTxs);
            return [multicallTx];
        }
        
        return mergedTxs;
    }
    
    // Create multicall transaction
    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 usage analysis
    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)
        };
        
        // Store history for future optimization
        this.gasHistory.set(tx.to, {
            ...analysis,
            timestamp: Date.now()
        });
        
        return analysis;
    }
}
```

#### Contract Call Optimization

```javascript
// Smart contract call optimizer
class ContractCallOptimizer {
    constructor(provider) {
        this.provider = provider;
        this.callDataCache = new Map();
    }
    
    // Optimize contract calls
    async optimizeContractCall(contract, method, params) {
        // Implementation continues...
    }
}
```


---

# 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/developer-documentation-for-jucoin-wallet/developer-guide/5.-more.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.
