# 4. API Reference

### Overview

Ju.com Wallet's Provider API is fully compatible with Ethereum's Provider standard while providing some extended features. The Provider object is exposed to DApps through `window.jcEthereum` or `window.ethereum` (compatibility mode).

### Provider Object

```javascript
// Provider Interface Definition
interface JuCoinProvider {
    // Standard properties
    isConnected(): boolean;               // Check connection status
    chainId: string | null;               // Current chain ID
    selectedAddress: string | null;       // Currently selected account address
    
    // Core methods
    request(args: RequestArguments): Promise<any>;
    
    // Event methods
    on(event: string, handler: Function): void;
    once(event: string, handler: Function): void;
    off(event: string, handler: Function): void;
    removeListener(event: string, handler: Function): void;
    removeAllListeners(event?: string): void;
    
    // Deprecated but still supported methods (backward compatibility)
    enable(): Promise<string[]>;
    send(method: string, params?: any[]): Promise<any>;
    sendAsync(payload: any, callback: Function): void;
}
```

#### Basic Usage

```javascript
// Get provider
const provider = window.jucoin || window.ethereum;

// Check if it's JuCoin Wallet
if (provider?.isJuCoin) {
    console.log('JuCoin Wallet detected');
}

// Check connection status
if (provider.isConnected()) {
    console.log('Connected to blockchain network');
}

// Get current account
const account = provider.selectedAddress;

// Get current chain ID
const chainId = provider.chainId;
```

#### request Method

This is the primary method for interacting with JuCoin Wallet:

```javascript
// request method signature
provider.request({
    method: string,
    params?: Array<any> | Object
}): Promise<any>

// Usage example
try {
    const result = await provider.request({
        method: 'method_name',
        params: [param1, param2, ...]
    });
    console.log('Result:', result);
} catch (error) {
    console.error('Error:', error);
}
```

#### Event Listeners

```javascript
// Account changed event
provider.on('accountsChanged', (accounts) => {
    if (accounts.length === 0) {
        console.log('Wallet disconnected');
    } else {
        console.log('Current account:', accounts[0]);
    }
});

// Chain changed event
provider.on('chainChanged', (chainId) => {
    console.log('Switched to chain:', chainId);
    // Recommend refreshing page to ensure consistent state
    window.location.reload();
});

// Connect event
provider.on('connect', (connectInfo) => {
    console.log('Connected, chain ID:', connectInfo.chainId);
});

// Disconnect event
provider.on('disconnect', (error) => {
    console.log('Disconnected:', error);
});

// Message event (for monitoring wallet internal messages)
provider.on('message', (message) => {
    console.log('Wallet message:', message);
});
```

#### Error Handling

```javascript
// Provider Error Codes
const ProviderErrors = {
    // User rejection error
    4001: 'User Rejected Request',
    
    // Unauthorized error
    4100: 'Unauthorized',
    
    // Unsupported method
    4200: 'Unsupported Method',
    
    // Disconnected
    4900: 'Disconnected',
    
    // Chain disconnected
    4901: 'Chain Disconnected',
    
    // Internal error
    -32603: 'Internal Error',
    
    // Invalid parameters
    -32602: 'Invalid Params',
    
    // Method not found
    -32601: 'Method Not Found',
    
    // Request limit exceeded
    -32005: 'Request Limit Exceeded'
};

// Error handling example
try {
    const accounts = await provider.request({
        method: 'eth_requestAccounts'
    });
} catch (error) {
    switch (error.code) {
        case 4001:
            console.log('User rejected connection request');
            break;
        case -32002:
            console.log('Request already pending, please check wallet');
            break;
        default:
            console.error('Unknown error:', error);
    }
}
```

### Ethereum JSON-RPC

Ju.com Wallet supports all standard Ethereum JSON-RPC methods. Here are detailed descriptions of commonly used methods:

#### Account Related Methods

**eth\_requestAccounts**

Request user authorization to access accounts:

```javascript
// Request wallet connection
const accounts = await provider.request({
    method: 'eth_requestAccounts'
});
// Return value: string[] - Array of user-authorized account addresses
// Example: ['0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0']
```

**eth\_accounts**

Get current authorized account list:

```javascript
// Get connected accounts
const accounts = await provider.request({
    method: 'eth_accounts'
});
// Return value: string[] - Array of authorized account addresses
// Returns empty array [] if not connected
```

#### Transaction Related Methods

**eth\_sendTransaction**

Send transaction:

```javascript
// Send ETH
const transactionHash = await provider.request({
    method: 'eth_sendTransaction',
    params: [{
        from: '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        to: '0x5aeda56215b167893e80b4fe645ba6d5bab767de',
        value: '0x29a2241af62c0000',  // 3 ETH in wei
        gas: '0x5208',  // 21000
        gasPrice: '0x4a817c800'  // 20 Gwei
    }]
});

// Call smart contract
const txHash = await provider.request({
    method: 'eth_sendTransaction',
    params: [{
        from: '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        to: '0xContractAddress',
        data: '0x095ea7b3...', // Contract call data
        gas: '0x186a0',  // 100000
        gasPrice: '0x4a817c800'
    }]
});

// EIP-1559 transaction
const txHash = await provider.request({
    method: 'eth_sendTransaction',
    params: [{
        from: '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        to: '0x5aeda56215b167893e80b4fe645ba6d5bab767de',
        value: '0x29a2241af62c0000',
        gas: '0x5208',
        maxFeePerGas: '0x9184e72a000',  // 10000 Gwei
        maxPriorityFeePerGas: '0x77359400',  // 2 Gwei
        type: '0x2'  // EIP-1559
    }]
});
```

**eth\_signTransaction**

Sign transaction without broadcasting:

```javascript
const signedTx = await provider.request({
    method: 'eth_signTransaction',
    params: [{
        from: '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        to: '0x5aeda56215b167893e80b4fe645ba6d5bab767de',
        value: '0x29a2241af62c0000',
        gas: '0x5208',
        gasPrice: '0x4a817c800',
        nonce: '0x0'
    }]
});
// Returns signed transaction data
// Can be broadcasted using eth_sendRawTransaction
```

#### Signature Related Methods

**personal\_sign**

Sign message:

```javascript
const message = 'Hello JuCoin!';
const accounts = await provider.request({ method: 'eth_accounts' });
const account = accounts[0];

// Convert message to hex
const hexMessage = '0x' + Buffer.from(message, 'utf8').toString('hex');

const signature = await provider.request({
    method: 'personal_sign',
    params: [hexMessage, account]
});

// Verify signature
const recoveredAddress = ethers.utils.verifyMessage(message, signature);
console.log('Signing address:', recoveredAddress);
```

**eth\_signTypedData\_v4**

Sign structured data (EIP-712):

```javascript
const typedData = {
    domain: {
        name: 'JuCoin Exchange',
        version: '1',
        chainId: 1,
        verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC'
    },
    types: {
        EIP712Domain: [
            { name: 'name', type: 'string' },
            { name: 'version', type: 'string' },
            { name: 'chainId', type: 'uint256' },
            { name: 'verifyingContract', type: 'address' }
        ],
        Order: [
            { name: 'maker', type: 'address' },
            { name: 'taker', type: 'address' },
            { name: 'tokenId', type: 'uint256' },
            { name: 'price', type: 'uint256' },
            { name: 'nonce', type: 'uint256' },
            { name: 'deadline', type: 'uint256' }
        ]
    },
    primaryType: 'Order',
    message: {
        maker: account,
        taker: '0x0000000000000000000000000000000000000000',
        tokenId: 1,
        price: '1000000000000000000',
        nonce: 0,
        deadline: Math.floor(Date.now() / 1000) + 3600
    }
};

const signature = await provider.request({
    method: 'eth_signTypedData_v4',
    params: [account, JSON.stringify(typedData)]
});
```

#### Query Methods

**eth\_getBalance**

Get account balance:

```javascript
const balance = await provider.request({
    method: 'eth_getBalance',
    params: [
        '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        'latest'  // Or specify block number
    ]
});
// Return value is wei in hexadecimal
// Convert to ETH
const balanceInEth = parseInt(balance, 16) / 1e18;
```

**eth\_getTransactionCount**

Get account nonce:

```javascript
const nonce = await provider.request({
    method: 'eth_getTransactionCount',
    params: [
        '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        'pending'  // Include pending transactions
    ]
});
console.log('Nonce:', parseInt(nonce, 16));
```

**eth\_estimateGas**

Estimate gas:

```javascript
const gasEstimate = await provider.request({
    method: 'eth_estimateGas',
    params: [{
        from: '0x742d35Cc6634C0532925a3b844Bc9e7095f0e5E0',
        to: '0x5aeda56215b167893e80b4fe645ba6d5bab767de',
        value: '0x29a2241af62c0000',
        data: '0x'
    }]
});
console.log('Estimated gas:', parseInt(gasEstimate, 16));
```

#### Network Related Methods

**eth\_chainId**

Get current chain ID:

```javascript
const chainId = await provider.request({
    method: 'eth_chainId'
});
console.log('Current chain ID:', chainId);
// 0x1 - Ethereum Mainnet
// 0x38 - BSC
// 0x8956 - JuChain
```

**wallet\_switchEthereumChain**

Switch network:

```javascript
try {
    await provider.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x38' }]  // Switch to BSC
    });
} catch (error) {
    if (error.code === 4902) {
        console.log('Network not added to user wallet');
    }
}
```

**wallet\_addEthereumChain**

Add custom network:

```javascript
try {
    await provider.request({
        method: 'wallet_addEthereumChain',
        params: [{
            chainId: '0x8956',
            chainName: 'JuChain Mainnet',
            nativeCurrency: {
                name: 'JU',
                symbol: 'JU',
                decimals: 18
            },
            rpcUrls: ['https://rpc.juchain.com'],
            blockExplorerUrls: ['https://explorer.juchain.com']
        }]
    });
} catch (error) {
    console.error('Failed to add network:', error);
}
```

### JuCoin Extension API (Coming Soon)

*Additional JuCoin-specific APIs will be supported in future versions.*


---

# 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/4.-api-reference.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.
