# 1. 快速入门

## 一、快速入门

### 5分钟完成DApp与Ju.com钱包的集成

Ju.com Web3钱包完全兼容以太坊生态系统，支持所有标准的Web3 API。如果您的DApp已经支持MetaMask，只需极少的修改即可支持Ju.com钱包。

#### 快速体验

创建一个简单的HTML文件，即可体验Ju.com钱包的基本功能：

```html
<!DOCTYPE html>
<html>
<head>
    <title>JuCoin快速集成</title>
</head>
<body>
    <h1>JuCoin钱包快速集成示例</h1>
    <button onclick="connectWallet()">连接钱包</button>
    <p id="account"></p>

    <script>
        async function connectWallet() {
            // 检测JuCoin钱包
            if (typeof window.jcWallet !== 'undefined') {
                try {
                    // 请求连接钱包
                    const accounts = await window.ethereum.request({
                        method: 'eth_requestAccounts'
                    });
                    
                    // 显示连接的账户
                    document.getElementById('account').innerText = 
                        '已连接账户: ' + accounts[0];
                } catch (error) {
                    console.error('用户拒绝连接:', error);
                }
            } else {
                alert('请先安装JuCoin钱包');
                window.open('https://www.jucoin.com/download', '_blank');
            }
        }
    </script>
</body>
</html>
```

#### 三步完成集成

**第一步：检测钱包**

```javascript
// JuCoin钱包会在window对象上注入jucoin和ethereum对象
const isJuCoinInstalled = () => {
    // 优先检测jucoin对象
    if (typeof window.jcWallet !== 'undefined') {
        return true;
    }
    
    // 兼容模式：检测ethereum对象上的isJuCoin标识
    if (typeof window.ethereum !== 'undefined') {
        return true;
    }
    
    return false;
};

// 获取provider对象
const getProvider = () => {
    if (window.jcWallet) return window.jcWallet.ethereum;
    if (typeof window.ethereum !== 'undefined') return window.ethereum;
    return null;
};
```

**第二步：连接钱包**

```javascript
async function connectJuCoinWallet() {
    const provider = getProvider();
    
    if (!provider) {
        console.log('JuCoin钱包未安装');
        // 引导用户安装
        window.open('https://www.jucoin.com/download', '_blank');
        return null;
    }
    
    try {
        // 请求用户授权连接钱包
        const accounts = await provider.request({
            method: 'eth_requestAccounts'
        });
        
        console.log('连接成功！账户地址:', accounts[0]);
        
        // 获取链ID
        const chainId = await provider.request({
            method: 'eth_chainId'
        });
        
        console.log('当前链ID:', chainId);
        
        return {
            account: accounts[0],
            chainId: chainId,
            provider: provider
        };
    } catch (error) {
        if (error.code === 4001) {
            // 用户拒绝连接
            console.log('用户取消了连接请求');
        } else {
            console.error('连接错误:', error);
        }
        return null;
    }
}
```

**第三步：发送交易**

```javascript
async function sendTransaction() {
    const provider = getProvider();
    
    if (!provider) {
        alert('请先安装JuCoin钱包');
        return;
    }
    
    try {
        const accounts = await provider.request({
            method: 'eth_accounts'
        });
        
        if (accounts.length === 0) {
            alert('请先连接钱包');
            return;
        }
        
        // 构建交易参数
        const transactionParameters = {
            from: accounts[0],                          // 发送地址
            to: '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0', // 接收地址
            value: '0x29a2241af62c0000',               // 发送金额 (3 ETH in wei)
            gas: '0x5208',                             // Gas限制 (21000)
        };
        
        // 发送交易
        const txHash = await provider.request({
            method: 'eth_sendTransaction',
            params: [transactionParameters],
        });
        
        console.log('交易已发送！交易哈希:', txHash);
        
        // 可以在区块浏览器中查看交易
        console.log(`查看交易: https://etherscan.io/tx/${txHash}`);
        
        return txHash;
    } catch (error) {
        if (error.code === 4001) {
            console.log('用户取消了交易');
        } else {
            console.error('交易失败:', error);
        }
    }
}
```

#### 完整示例：一个简单的DApp

```javascript
// 完整的钱包管理类
class JuCoinWalletManager {
    constructor() {
        this.provider = null;
        this.account = null;
        this.chainId = null;
        this.connected = false;
    }
    
    // 初始化
    init() {
        // 检测钱包
        if (window.jcWallet) {
            this.provider = window.jcWallet.ethereum;
        } else if (window.ethereum) {
            this.provider = window.ethereum;
        }
        
        if (this.provider) {
            // 监听账户变化
            this.provider.on('accountsChanged', (accounts) => {
                this.handleAccountsChanged(accounts);
            });
            
            // 监听链变化
            this.provider.on('chainChanged', (chainId) => {
                this.handleChainChanged(chainId);
            });
            
            // 检查是否已经连接
            this.checkConnection();
        }
        
        return !!this.provider;
    }
    
    // 检查连接状态
    async checkConnection() {
        try {
            const accounts = await this.provider.request({
                method: 'eth_accounts'
            });
            
            if (accounts.length > 0) {
                this.account = accounts[0];
                this.chainId = await this.provider.request({
                    method: 'eth_chainId'
                });
                this.connected = true;
                console.log('钱包已连接:', this.account);
            }
        } catch (error) {
            console.error('检查连接状态失败:', error);
        }
    }
    
    // 连接钱包
    async connect() {
        if (!this.provider) {
            throw new Error('JuCoin钱包未安装');
        }
        
        try {
            const accounts = await this.provider.request({
                method: 'eth_requestAccounts'
            });
            
            this.account = accounts[0];
            this.chainId = await this.provider.request({
                method: 'eth_chainId'
            });
            this.connected = true;
            
            return {
                account: this.account,
                chainId: this.chainId
            };
        } catch (error) {
            throw error;
        }
    }
    
    // 获取余额
    async getBalance() {
        if (!this.connected) {
            throw new Error('钱包未连接');
        }
        
        const balance = await this.provider.request({
            method: 'eth_getBalance',
            params: [this.account, 'latest']
        });
        
        // 将wei转换为ETH
        return parseInt(balance, 16) / 1e18;
    }
    
    // 发送ETH
    async sendETH(to, amount) {
        if (!this.connected) {
            throw new Error('钱包未连接');
        }
        
        // 将ETH转换为wei
        const value = '0x' + Math.floor(amount * 1e18).toString(16);
        
        const txHash = await this.provider.request({
            method: 'eth_sendTransaction',
            params: [{
                from: this.account,
                to: to,
                value: value,
                gas: '0x5208'
            }]
        });
        
        return txHash;
    }
    
    // 处理账户变化
    handleAccountsChanged(accounts) {
        if (accounts.length === 0) {
            // 用户断开了钱包连接
            this.account = null;
            this.connected = false;
            console.log('钱包已断开连接');
        } else {
            this.account = accounts[0];
            console.log('账户已切换:', this.account);
        }
    }
    
    // 处理链变化
    handleChainChanged(chainId) {
        this.chainId = chainId;
        console.log('链已切换:', chainId);
        // 建议刷新页面以确保应用状态正确
        window.location.reload();
    }
}

// 使用示例
const wallet = new JuCoinWalletManager();

// 页面加载时初始化
window.addEventListener('load', async () => {
    if (wallet.init()) {
        console.log('JuCoin钱包已检测到');
    } else {
        console.log('请安装JuCoin钱包');
    }
});
```

### 环境准备

#### 开发环境要求

**1. 支持的浏览器**

Ju.com钱包支持所有现代浏览器：

* **Chrome** 90+ (推荐)
* **Firefox** 88+
* **Safari** 14+
* **Edge** 90+
* **Brave** 最新版本

移动端支持：

* Ju.com App 内置浏览器
* 支持 WalletConnect 协议的移动浏览器

**2. Node.js 和包管理器**

确保已安装 Node.js 14.0.0 或更高版本：

```bash
# 检查 Node.js 版本
node --version

# 检查 npm 版本
npm --version

# 或使用 yarn
yarn --version
```

**3. 开发框架（可选）**

Ju.com钱包支持所有主流前端框架：

```bash
# React
npx create-react-app my-jucoin-dapp
cd my-jucoin-dapp

# Vue
npm create vue@latest my-jucoin-dapp
cd my-jucoin-dapp

# Next.js
npx create-next-app@latest my-jucoin-dapp
cd my-jucoin-dapp

# 原生 JavaScript (使用 Vite)
npm create vite@latest my-jucoin-dapp -- --template vanilla
cd my-jucoin-dapp
```

#### Web3 库安装

**推荐：Ethers.js**

```bash
# 安装 ethers.js
npm install ethers

# 或使用 yarn
yarn add ethers
```

使用示例：

```javascript
import { ethers } from 'ethers';

// 创建 provider
const provider = new ethers.providers.Web3Provider(window.ethereum);

// 获取 signer
const signer = provider.getSigner();

// 获取账户地址
const address = await signer.getAddress();

// 获取余额
const balance = await signer.getBalance();
console.log('余额:', ethers.utils.formatEther(balance), 'ETH');
```

**备选：Web3.js**

```bash
# 安装 web3.js
npm install web3

# 或使用 yarn
yarn add web3
```

使用示例：

```javascript
import Web3 from 'web3';

// 创建 web3 实例
const web3 = new Web3(window.ethereum);

// 获取账户
const accounts = await web3.eth.getAccounts();

// 获取余额
const balance = await web3.eth.getBalance(accounts[0]);
console.log('余额:', web3.utils.fromWei(balance, 'ether'), 'ETH');
```

#### 本地开发服务器

**HTTPS 配置**

出于安全考虑，Ju.com钱包只在安全环境下工作：

* HTTPS 网站
* `http://localhost`
* `http://127.0.0.1`

本地开发HTTPS配置：

```bash
# 使用 Vite (自带 HTTPS 支持)
npm create vite@latest my-dapp
cd my-dapp
npm install
npm run dev -- --https

# 使用 mkcert 创建本地证书
# macOS
brew install mkcert
mkcert -install
mkcert localhost

# Windows (使用 chocolatey)
choco install mkcert
mkcert -install
mkcert localhost

# 在项目中使用证书
# vite.config.js
import { defineConfig } from 'vite'
import fs from 'fs'

export default defineConfig({
  server: {
    https: {
      key: fs.readFileSync('./localhost-key.pem'),
      cert: fs.readFileSync('./localhost.pem'),
    }
  }
})
```

#### 测试网络配置

**JuChain 测试网**

```javascript
const JUCHAIN_TESTNET = {
    chainId: '0x89ab',  // 35243 in decimal
    chainName: 'JuChain Testnet',
    nativeCurrency: {
        name: 'Test JU',
        symbol: 'tJU',
        decimals: 18
    },
    rpcUrls: ['https://testnet-rpc.juchain.com'],
    blockExplorerUrls: ['https://testnet-explorer.juchain.com']
};

// 添加测试网到钱包
async function addJuChainTestnet() {
    try {
        await window.jucoin.request({
            method: 'wallet_addEthereumChain',
            params: [JUCHAIN_TESTNET]
        });
        console.log('JuChain测试网添加成功');
    } catch (error) {
        console.error('添加网络失败:', error);
    }
}
```

**获取测试代币**

1. 访问 [JuChain 水龙头](https://faucet-testnet.juchain.org/)
2. 连接您的Ju.com钱包
3. 输入验证码
4. 点击"领取测试币"


---

# 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/1.-kuai-su-ru-men.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.
