# 2. Core Concepts

### Account System

#### Overview

Ju.com Wallet adopts a Hierarchical Deterministic (HD) wallet architecture, following BIP-32, BIP-39, and BIP-44 standards. Each user can manage multiple accounts, each with independent addresses and private keys, but all derived from the same seed phrase (mnemonic).

#### Account Generation Principles

```javascript
// JuCoin Account System Diagram
/*
 Mnemonic (12/24 words)
    ↓
 Seed (512 bits)
    ↓
 Master Private Key (256 bits)
    ↓
 Derivation Path: m/44'/60'/0'/0/x
    ↓
 Account Private Key → Public Key → Address
*/

// Account address generation process
class AccountSystem {
    // Generate seed from mnemonic
    generateSeed(mnemonic) {
        // Using PBKDF2 algorithm with 2048 iterations
        // Salt is "mnemonic" + passphrase
        return pbkdf2(mnemonic, "mnemonic" + passphrase, 2048, 64, 'sha512');
    }
    
    // Generate master private key from seed
    generateMasterKey(seed) {
        // Using HMAC-SHA512 algorithm
        const hmac = createHmac('sha512', 'Bitcoin seed');
        const hash = hmac.update(seed).digest();
        
        return {
            privateKey: hash.slice(0, 32),
            chainCode: hash.slice(32)
        };
    }
    
    // Derive account
    deriveAccount(masterKey, index) {
        // Using BIP-44 standard path
        // m/44'/60'/0'/0/index
        // 44' - BIP-44 standard
        // 60' - Ethereum coin type
        // 0'  - Account
        // 0   - External chain
        // index - Address index
        
        const path = `m/44'/60'/0'/0/${index}`;
        return this.derivePath(masterKey, path);
    }
    
    // Generate address from private key
    privateKeyToAddress(privateKey) {
        // 1. Generate public key (using secp256k1 elliptic curve)
        const publicKey = secp256k1.publicKeyCreate(privateKey, false);
        
        // 2. Keccak-256 hash of public key
        const publicKeyHash = keccak256(publicKey.slice(1));
        
        // 3. Take last 20 bytes as address
        const address = '0x' + publicKeyHash.slice(-20).toString('hex');
        
        return address;
    }
}
```

#### Account Management

```javascript
// JuCoin Account Management Interface
class JuCoinAccountManager {
    // Get all accounts
    async getAccounts() {
        const accounts = await window.jucoin.request({
            method: 'eth_accounts'
        });
        return accounts;
    }
    
    // Get detailed account information (JuCoin extension)
    async getAccountsInfo() {
        const accountsInfo = await window.jucoin.request({
            method: 'jucoin_getAccountsInfo'
        });
        
        // Return format
        // [{
        //     address: '0x...',
        //     name: 'Account 1',
        //     balance: '1000000000000000000',
        //     type: 'HD',  // HD or Imported
        //     index: 0     // HD account index
        // }]
        
        return accountsInfo;
    }
    
    // Create new account (requires wallet password)
    async createAccount(accountName) {
        const newAccount = await window.jucoin.request({
            method: 'jucoin_createAccount',
            params: [{ name: accountName }]
        });
        return newAccount;
    }
    
    // Import account (via private key)
    async importAccount(privateKey, accountName) {
        const importedAccount = await window.jucoin.request({
            method: 'jucoin_importAccount',
            params: [{
                privateKey: privateKey,
                name: accountName
            }]
        });
        return importedAccount;
    }
    
    // Switch current account
    async switchAccount(address) {
        const result = await window.jucoin.request({
            method: 'jucoin_switchAccount',
            params: [address]
        });
        return result;
    }
}
```

#### Account Permission Management

```javascript
// Permission levels
const PermissionLevels = {
    NONE: 0,           // No permission
    VIEW: 1,           // View permission (can view address and balance)
    SIGN: 2,           // Sign permission (can sign messages)
    TRANSACTION: 3,    // Transaction permission (can send transactions)
    FULL: 4           // Full permission
};

// Permission management
class PermissionManager {
    // Request permissions
    async requestPermissions(permissions) {
        const granted = await window.jucoin.request({
            method: 'wallet_requestPermissions',
            params: [permissions]
        });
        return granted;
    }
    
    // Get current permissions
    async getPermissions() {
        const permissions = await window.jucoin.request({
            method: 'wallet_getPermissions'
        });
        return permissions;
    }
    
    // Check specific permission
    hasPermission(permissions, method) {
        return permissions.some(p => 
            p.parentCapability === method || 
            p.parentCapability === 'eth_accounts'
        );
    }
}
```

### Transaction Signing

#### Signature Types

JuCoin Wallet supports multiple signature types to meet different use cases:

```javascript
// 1. Transaction signature (eth_sendTransaction)
// Used for sending ETH or calling contracts
const txSignature = await window.jucoin.request({
    method: 'eth_sendTransaction',
    params: [{
        from: '0x...',
        to: '0x...',
        value: '0x...',
        data: '0x...',
        gas: '0x...',
        gasPrice: '0x...'
    }]
});

// 2. Message signature (personal_sign)
// Used to prove account ownership
const msgSignature = await window.jucoin.request({
    method: 'personal_sign',
    params: [
        '0x48656c6c6f20576f726c64',  // "Hello World" in hex
        '0x...'  // Signing account
    ]
});

// 3. Typed data signature (eth_signTypedData_v4)
// Used for structured data signing, such as orders, authorizations, etc.
const typedSignature = await window.jucoin.request({
    method: 'eth_signTypedData_v4',
    params: [
        '0x...',  // Signing account
        JSON.stringify(typedData)
    ]
});
```

#### Transaction Signing Process

```javascript
// Complete transaction signing process
class TransactionSigner {
    constructor(provider) {
        this.provider = provider;
    }
    
    // 1. Build transaction
    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. Sign transaction
    async signTransaction(transaction) {
        // Using eth_signTransaction to sign only without broadcasting
        const signedTx = await this.provider.request({
            method: 'eth_signTransaction',
            params: [transaction]
        });
        return signedTx;
    }
    
    // 3. Send signed transaction
    async sendSignedTransaction(signedTx) {
        const txHash = await this.provider.request({
            method: 'eth_sendRawTransaction',
            params: [signedTx]
        });
        return txHash;
    }
    
    // One step: sign and send
    async signAndSendTransaction(params) {
        const transaction = await this.buildTransaction(params);
        const txHash = await this.provider.request({
            method: 'eth_sendTransaction',
            params: [transaction]
        });
        return txHash;
    }
}
```

#### EIP-712 Typed Data Signature

```javascript
// EIP-712 signature for structured data
class EIP712Signer {
    // Build EIP-712 message
    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
        };
    }
    
    // Signature example: signing an order
    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;
    }
    
    // Verify signature
    verifySignature(typedData, signature, expectedSigner) {
        const recoveredAddress = ethers.utils.verifyTypedData(
            typedData.domain,
            typedData.types,
            typedData.message,
            signature
        );
        
        return recoveredAddress.toLowerCase() === expectedSigner.toLowerCase();
    }
}
```

### Network Configuration

#### Currently Supported Networks

Ju.com Wallet currently supports the following three EVM-compatible public chains:

```javascript
// Currently supported network configurations
const SUPPORTED_NETWORKS = {
    // JuChain Mainnet
    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 Mainnet
    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 Mainnet
    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']
    }
};

// Testnet configurations
const TESTNET_NETWORKS = {
    // JuChain Testnet
    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 Testnet
    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 Testnet
    BSC_TESTNET: {
        chainId: '0x61',  // 97
        chainName: 'BSC Testnet',
        nativeCurrency: {
            name: 'Test BNB',
            symbol: 'tBNB',
            decimals: 18
        },
        rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545'],
        blockExplorerUrls: ['https://testnet.bscscan.com']
    }
};
```


---

# 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/2.-core-concepts.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.
