# 2. 核心概念

### 账户体系

#### 概述

Ju.com钱包采用分层确定性（HD）钱包架构，遵循BIP-32、BIP-39和BIP-44标准。每个用户可以管理多个账户，每个账户都有独立的地址和私钥，但都源自同一个种子短语（助记词）。

#### 账户生成原理

```javascript
// JuCoin账户体系示意图
/*
 助记词 (12/24个单词)
    ↓
 种子 (512位)
    ↓
 主私钥 (256位)
    ↓
 派生路径: m/44'/60'/0'/0/x
    ↓
 账户私钥 → 公钥 → 地址
*/

// 账户地址生成过程
class AccountSystem {
    // 从助记词生成种子
    generateSeed(mnemonic) {
        // 使用PBKDF2算法，迭代2048次
        // 盐值为"mnemonic" + passphrase
        return pbkdf2(mnemonic, "mnemonic" + passphrase, 2048, 64, 'sha512');
    }
    
    // 从种子生成主私钥
    generateMasterKey(seed) {
        // 使用HMAC-SHA512算法
        const hmac = createHmac('sha512', 'Bitcoin seed');
        const hash = hmac.update(seed).digest();
        
        return {
            privateKey: hash.slice(0, 32),
            chainCode: hash.slice(32)
        };
    }
    
    // 派生账户
    deriveAccount(masterKey, index) {
        // 使用BIP-44标准路径
        // m/44'/60'/0'/0/index
        // 44' - BIP-44标准
        // 60' - 以太坊币种
        // 0'  - 账户
        // 0   - 外部链
        // index - 地址索引
        
        const path = `m/44'/60'/0'/0/${index}`;
        return this.derivePath(masterKey, path);
    }
    
    // 从私钥生成地址
    privateKeyToAddress(privateKey) {
        // 1. 生成公钥（使用secp256k1椭圆曲线）
        const publicKey = secp256k1.publicKeyCreate(privateKey, false);
        
        // 2. 对公钥进行Keccak-256哈希
        const publicKeyHash = keccak256(publicKey.slice(1));
        
        // 3. 取最后20字节作为地址
        const address = '0x' + publicKeyHash.slice(-20).toString('hex');
        
        return address;
    }
}
```

#### 账户管理

```javascript
// JuCoin账户管理接口
class JuCoinAccountManager {
    // 获取所有账户
    async getAccounts() {
        const accounts = await window.jucoin.request({
            method: 'eth_accounts'
        });
        return accounts;
    }
    
    // 获取账户详细信息（JuCoin扩展）
    async getAccountsInfo() {
        const accountsInfo = await window.jucoin.request({
            method: 'jucoin_getAccountsInfo'
        });
        
        // 返回格式
        // [{
        //     address: '0x...',
        //     name: 'Account 1',
        //     balance: '1000000000000000000',
        //     type: 'HD',  // HD或Imported
        //     index: 0     // HD账户的索引
        // }]
        
        return accountsInfo;
    }
    
    // 创建新账户（需要钱包密码）
    async createAccount(accountName) {
        const newAccount = await window.jucoin.request({
            method: 'jucoin_createAccount',
            params: [{ name: accountName }]
        });
        return newAccount;
    }
    
    // 导入账户（通过私钥）
    async importAccount(privateKey, accountName) {
        const importedAccount = await window.jucoin.request({
            method: 'jucoin_importAccount',
            params: [{
                privateKey: privateKey,
                name: accountName
            }]
        });
        return importedAccount;
    }
    
    // 切换当前账户
    async switchAccount(address) {
        const result = await window.jucoin.request({
            method: 'jucoin_switchAccount',
            params: [address]
        });
        return result;
    }
}
```

#### 账户权限管理

```javascript
// 权限级别
const PermissionLevels = {
    NONE: 0,           // 无权限
    VIEW: 1,           // 查看权限（可以查看地址和余额）
    SIGN: 2,           // 签名权限（可以签名消息）
    TRANSACTION: 3,    // 交易权限（可以发送交易）
    FULL: 4           // 完全权限
};

// 权限管理
class PermissionManager {
    // 请求权限
    async requestPermissions(permissions) {
        const granted = await window.jucoin.request({
            method: 'wallet_requestPermissions',
            params: [permissions]
        });
        return granted;
    }
    
    // 获取当前权限
    async getPermissions() {
        const permissions = await window.jucoin.request({
            method: 'wallet_getPermissions'
        });
        return permissions;
    }
    
    // 检查特定权限
    hasPermission(permissions, method) {
        return permissions.some(p => 
            p.parentCapability === method || 
            p.parentCapability === 'eth_accounts'
        );
    }
}
```

### 交易签名

#### 签名类型

Ju.com钱包支持多种签名类型，满足不同的使用场景：

```javascript
// 1. 交易签名（eth_sendTransaction）
// 用于发送ETH或调用合约
const txSignature = await window.jucoin.request({
    method: 'eth_sendTransaction',
    params: [{
        from: '0x...',
        to: '0x...',
        value: '0x...',
        data: '0x...',
        gas: '0x...',
        gasPrice: '0x...'
    }]
});

// 2. 消息签名（personal_sign）
// 用于证明账户所有权
const msgSignature = await window.jucoin.request({
    method: 'personal_sign',
    params: [
        '0x48656c6c6f20576f726c64',  // "Hello World" in hex
        '0x...'  // 签名账户
    ]
});

// 3. 类型化数据签名（eth_signTypedData_v4）
// 用于结构化数据签名，如订单、授权等
const typedSignature = await window.jucoin.request({
    method: 'eth_signTypedData_v4',
    params: [
        '0x...',  // 签名账户
        JSON.stringify(typedData)
    ]
});
```

#### 交易签名流程

```javascript
// 完整的交易签名流程
class TransactionSigner {
    constructor(provider) {
        this.provider = provider;
    }
    
    // 1. 构建交易
    async buildTransaction(params) {
        const nonce = await this.provider.request({
            method: 'eth_getTransactionCount',
            params: [params.from, 'latest']
        });
        
        const gasPrice = await this.provider.request({
            method: 'eth_gasPrice'
        });
        
        const gasLimit = await this.provider.request({
            method: 'eth_estimateGas',
            params: [{
                from: params.from,
                to: params.to,
                value: params.value || '0x0',
                data: params.data || '0x'
            }]
        });
        
        return {
            from: params.from,
            to: params.to,
            value: params.value || '0x0',
            data: params.data || '0x',
            nonce: nonce,
            gasPrice: gasPrice,
            gas: gasLimit,
            chainId: await this.provider.request({ method: 'eth_chainId' })
        };
    }
    
    // 2. 签名交易
    async signTransaction(transaction) {
        // 使用 eth_signTransaction 只签名不广播
        const signedTx = await this.provider.request({
            method: 'eth_signTransaction',
            params: [transaction]
        });
        return signedTx;
    }
    
    // 3. 发送已签名交易
    async sendSignedTransaction(signedTx) {
        const txHash = await this.provider.request({
            method: 'eth_sendRawTransaction',
            params: [signedTx]
        });
        return txHash;
    }
    
    // 一步完成：签名并发送
    async signAndSendTransaction(params) {
        const transaction = await this.buildTransaction(params);
        const txHash = await this.provider.request({
            method: 'eth_sendTransaction',
            params: [transaction]
        });
        return txHash;
    }
}
```

#### EIP-712 类型化数据签名

```javascript
// EIP-712 签名用于结构化数据
class EIP712Signer {
    // 构建EIP-712消息
    buildTypedData(domain, types, primaryType, message) {
        return {
            types: {
                EIP712Domain: [
                    { name: 'name', type: 'string' },
                    { name: 'version', type: 'string' },
                    { name: 'chainId', type: 'uint256' },
                    { name: 'verifyingContract', type: 'address' }
                ],
                ...types
            },
            primaryType: primaryType,
            domain: domain,
            message: message
        };
    }
    
    // 签名示例：签署订单
    async signOrder(order) {
        const domain = {
            name: 'JuCoin Exchange',
            version: '1',
            chainId: 1,
            verifyingContract: '0x...'
        };
        
        const types = {
            Order: [
                { name: 'maker', type: 'address' },
                { name: 'taker', type: 'address' },
                { name: 'tokenA', type: 'address' },
                { name: 'tokenB', type: 'address' },
                { name: 'amountA', type: 'uint256' },
                { name: 'amountB', type: 'uint256' },
                { name: 'nonce', type: 'uint256' },
                { name: 'deadline', type: 'uint256' }
            ]
        };
        
        const typedData = this.buildTypedData(
            domain,
            types,
            'Order',
            order
        );
        
        const signature = await window.jucoin.request({
            method: 'eth_signTypedData_v4',
            params: [order.maker, JSON.stringify(typedData)]
        });
        
        return signature;
    }
    
    // 验证签名
    verifySignature(typedData, signature, expectedSigner) {
        const recoveredAddress = ethers.utils.verifyTypedData(
            typedData.domain,
            typedData.types,
            typedData.message,
            signature
        );
        
        return recoveredAddress.toLowerCase() === expectedSigner.toLowerCase();
    }
}
```

### 网络配置

#### 当前支持的网络

Ju.com钱包当前版本支持以下三条EVM兼容公链：

```javascript
// 当前支持的网络配置
const SUPPORTED_NETWORKS = {
    // JuChain主网
    JUCHAIN: {
        chainId: '0x8956',  // 35158
        chainName: 'JuChain Mainnet',
        nativeCurrency: {
            name: 'JU',
            symbol: 'JU',
            decimals: 18
        },
        rpcUrls: ['https://rpc.juchain.com'],
        blockExplorerUrls: ['https://explorer.juchain.com'],
        iconUrls: ['https://assets.jucoin.com/juchain-icon.png']
    },
    
    // 以太坊主网
    ETHEREUM: {
        chainId: '0x1',  // 1
        chainName: 'Ethereum Mainnet',
        nativeCurrency: {
            name: 'Ethereum',
            symbol: 'ETH',
            decimals: 18
        },
        rpcUrls: ['https://mainnet.infura.io/v3/YOUR-PROJECT-ID'],
        blockExplorerUrls: ['https://etherscan.io'],
        iconUrls: ['https://assets.jucoin.com/eth-icon.png']
    },
    
    // BNB Smart Chain主网
    BSC: {
        chainId: '0x38',  // 56
        chainName: 'BNB Smart Chain',
        nativeCurrency: {
            name: 'BNB',
            symbol: 'BNB',
            decimals: 18
        },
        rpcUrls: ['https://bsc-dataseed.binance.org'],
        blockExplorerUrls: ['https://bscscan.com'],
        iconUrls: ['https://assets.jucoin.com/bnb-icon.png']
    }
};

// 测试网配置
const TESTNET_NETWORKS = {
    // JuChain测试网
    JUCHAIN_TESTNET: {
        chainId: '0x89ab',  // 35243
        chainName: 'JuChain Testnet',
        nativeCurrency: {
            name: 'Test JU',
            symbol: 'tJU',
            decimals: 18
        },
        rpcUrls: ['https://testnet-rpc.juchain.com'],
        blockExplorerUrls: ['https://testnet-explorer.juchain.com']
    },
    
    // Goerli测试网
    GOERLI: {
        chainId: '0x5',  // 5
        chainName: 'Goerli Testnet',
        nativeCurrency: {
            name: 'Goerli ETH',
            symbol: 'ETH',
            decimals: 18
        },
        rpcUrls: ['https://goerli.infura.io/v3/YOUR-PROJECT-ID'],
        blockExplorerUrls: ['https://goerli.etherscan.io']
    },
    
    // BSC测试网
    BSC_TESTNET: {
        chainId: '0x61',  // 97
        chainName: 'BSC Testnet',
        nativeCurrency: {
            name: 'Test BNB',
            symbol: 'tBNB',
            decimals: 18
        },
        rpcUrls: ['https://data-seed-prebsc
```


---

# 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/kai-fa-zhe-zhi-nan/2.-he-xin-gai-nian.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.
