# Connect Wallet

### Supported Wallets

| Wallet          | Desktop | Mobile | Browser Extension | Hardware |
| --------------- | ------- | ------ | ----------------- | -------- |
| MetaMask        | ✅       | ✅      | ✅                 | ✅        |
| Trust Wallet    | ❌       | ✅      | ✅                 | ❌        |
| Coinbase Wallet | ✅       | ✅      | ✅                 | ❌        |
| Rainbow         | ❌       | ✅      | ✅                 | ❌        |
| Ledger          | ✅       | ❌      | ❌                 | ✅        |
| Trezor          | ✅       | ❌      | ❌                 | ✅        |
| WalletConnect   | ✅       | ✅      | ❌                 | ❌        |

### MetaMask Setup

MetaMask is the most popular and recommended wallet for OPN Chain.

#### Browser Extension

1. **Install MetaMask**
   * [Chrome/Brave](https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn)
   * [Firefox](https://addons.mozilla.org/en-US/firefox/addon/ether-metamask/)
2. **Create or Import Wallet**
   * Follow MetaMask's setup wizard
   * Securely store your seed phrase
   * Never share your private key or seed phrase
3. **Add OPN Network**

   **Option A: Automatic (Recommended)**

   ```javascript
   // Add this to your website
   async function addOPNNetwork() {
     try {
       await window.ethereum.request({
         method: 'wallet_addEthereumChain',
         params: [{
           chainId: '0x3d8',
           chainName: 'OPN Testnet',
           nativeCurrency: {
             name: 'Test OPN',
             symbol: 'OPN',
             decimals: 18
           },
           rpcUrls: ['https://testnet-rpc.iopn.tech'],
           blockExplorerUrls: []
         }]
       });
     } catch (error) {
       console.error('Failed to add network:', error);
     }
   }
   ```

   **Option B: Manual**

   * Click the network dropdown
   * Select "Add Network"
   * Click "Add a network manually"
   * Enter:
     * **Network Name**: OPN Testnet
     * **RPC URL**: <https://testnet-rpc.iopn.tech>
     * **Chain ID**: 984
     * **Currency Symbol**: OPN

### Mobile Setup

1. **Download MetaMask Mobile**
   * [iOS App Store](https://apps.apple.com/us/app/metamask-blockchain-wallet/id1438144202)
   * [Android Play Store](https://play.google.com/store/apps/details?id=io.metamask)
2. **Import or Create Wallet**
   * Use same seed phrase as desktop for sync
   * Or create new mobile-only wallet
3. **Add OPN Network**
   * Go to Settings → Networks
   * Tap "Add Network"
   * Enter the network details above

### Connecting Hardware Wallets

MetaMask supports Ledger and Trezor hardware wallets:

1. **Connect Hardware Wallet**
   * Plug in your device
   * In MetaMask, go to Settings → Advanced
   * Enable "Use hardware wallets"
2. **Add Hardware Account**
   * Click account dropdown → Connect hardware wallet
   * Select your device type
   * Follow on-screen instructions
3. **Use with OPN Chain**
   * Ensure OPN network is selected
   * Hardware wallet will sign transactions

### Trust Wallet Setup

Trust Wallet is popular for mobile users.

### Mobile Setup

1. **Download Trust Wallet**
   * [iOS](https://apps.apple.com/app/trust-crypto-bitcoin-wallet/id1288339409)
   * [Android](https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp)
2. **Add Custom Network**

   * Go to Settings → Networks
   * Tap the + icon
   * Select "Custom Network"
   * Enter:

   ```
        Network: OPN Testnet
        RPC URL: https://testnet-rpc.iopn.tech
        Chain ID: 984
        Symbol: OPN
        Block Explorer: https://testnet.iopn.tech
   ```

#### Browser Extension

1. **Install Trust Wallet Extension**
   * Available for Chrome, Brave, Edge
2. **Configure Network**
   * Click settings icon
   * Select "Custom Networks"
   * Add OPN details

### Coinbase Wallet Setup

#### Browser Extension

1. **Install Extension**
   * [Chrome Web Store](https://chrome.google.com/webstore/detail/coinbase-wallet-extension/hnfanknocfeofbddgcijnmhnfnkdnaad)
2. **Add Network**
   * Click Settings → Networks
   * Add Custom Network
   * Enter OPN details

### Mobile Setup

1. **Download App**
   * [iOS](https://apps.apple.com/app/coinbase-wallet/id1278383455)
   * [Android](https://play.google.com/store/apps/details?id=org.toshi)
2. **Configure Network**
   * Settings → Networks → Add Network
   * Enter OPN configuration

### WalletConnect Integration

WalletConnect allows you to connect any compatible wallet to DApps.

#### For DApp Developers

```javascript
import WalletConnectProvider from "@walletconnect/web3-provider";
import Web3 from "web3";

// Initialize WalletConnect
const provider = new WalletConnectProvider({
  rpc: {
    984: "https://testnet-rpc.iopn.tech",
  },
  chainId: 984,
});

// Enable session
await provider.enable();

// Create Web3 instance
const web3 = new Web3(provider);

// Now you can use web3 as normal
const accounts = await web3.eth.getAccounts();
```

#### For Users

1. **Open DApp** that supports WalletConnect
2. **Click Connect Wallet** → WalletConnect
3. **Scan QR Code** with your mobile wallet
4. **Approve Connection** in your wallet

### Programmatic Wallet Connection

#### Detect Installed Wallets

```javascript
// Check for injected wallets
function getInstalledWallets() {
  const wallets = [];
  
  if (typeof window.ethereum !== 'undefined') {
    // MetaMask or compatible
    if (window.ethereum.isMetaMask) {
      wallets.push('MetaMask');
    }
    
    // Coinbase Wallet
    if (window.ethereum.isCoinbaseWallet) {
      wallets.push('Coinbase Wallet');
    }
    
    // Trust Wallet
    if (window.ethereum.isTrust) {
      wallets.push('Trust Wallet');
    }
  }
  
  return wallets;
}
```

#### Universal Connection Handler

```javascript
class WalletConnector {
  constructor() {
    this.provider = null;
    this.accounts = [];
    this.chainId = null;
  }
  
  async connect() {
    // Check if wallet is installed
    if (typeof window.ethereum === 'undefined') {
      throw new Error('No wallet detected. Please install MetaMask!');
    }
    
    try {
      // Request account access
      this.accounts = await window.ethereum.request({ 
        method: 'eth_requestAccounts' 
      });
      
      // Get chain ID
      this.chainId = await window.ethereum.request({ 
        method: 'eth_chainId' 
      });
      
      // Check if on OPN Chain
      if (parseInt(this.chainId, 16) !== 984) {
        await this.switchToOPN();
      }
      
      // Set provider
      this.provider = window.ethereum;
      
      // Setup event listeners
      this.setupEventListeners();
      
      return this.accounts[0];
      
    } catch (error) {
      console.error('Failed to connect:', error);
      throw error;
    }
  }
  
  async switchToOPN() {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x3d8' }],
      });
    } catch (switchError) {
      // Chain not added yet
      if (switchError.code === 4902) {
        await this.addOPNNetwork();
      }
    }
  }
  
  async addOPNNetwork() {
    await window.ethereum.request({
      method: 'wallet_addEthereumChain',
      params: [{
        chainId: '0x3d8',
        chainName: 'OPN Testnet',
        nativeCurrency: {
          name: 'Test OPN',
          symbol: 'OPN',
          decimals: 18
        },
        rpcUrls: ['https://testnet-rpc.iopn.tech'],
        blockExplorerUrls: []
      }],
    });
  }
  
  setupEventListeners() {
    window.ethereum.on('accountsChanged', (accounts) => {
      this.accounts = accounts;
      console.log('Accounts changed:', accounts);
    });
    
    window.ethereum.on('chainChanged', (chainId) => {
      this.chainId = chainId;
      console.log('Chain changed:', chainId);
      // Reload page on chain change
      window.location.reload();
    });
  }
  
  async disconnect() {
    // Note: There's no real "disconnect" in injected wallets
    // This is more for cleaning up state
    this.provider = null;
    this.accounts = [];
    this.chainId = null;
  }
}

// Usage
const wallet = new WalletConnector();
const account = await wallet.connect();
console.log('Connected account:', account);
```

### Security Best Practices

#### For Users

1. **Verify Network Details**
   * Always double-check RPC URL
   * Confirm Chain ID is 984
   * Only use official URLs
2. **Protect Your Keys**
   * Never share private keys
   * Never enter seed phrase on websites
   * Use hardware wallets for large amounts
3. **Check Transaction Details**
   * Verify recipient address
   * Check gas fees
   * Understand what you're signing

### For Developers

1. **Always Request Permissions**

   ```javascript
   // Bad - assumes permission
   const accounts = await web3.eth.getAccounts();

   // Good - requests permission
   const accounts = await window.ethereum.request({ 
     method: 'eth_requestAccounts' 
   });
   ```
2. **Handle Network Changes**

   ```javascript
   window.ethereum.on('chainChanged', (chainId) => {
     if (parseInt(chainId, 16) !== 984) {
       alert('Please switch to OPN Network');
     }
   });
   ```
3. **Validate User Input**

   ```javascript
   function isValidAddress(address) {
     return /^0x[a-fA-F0-9]{40}$/.test(address);
   }
   ```

### Common Issues

#### MetaMask Not Detected

```javascript
// Wait for page load
if (document.readyState !== 'loading') {
  detectMetaMask();
} else {
  document.addEventListener('DOMContentLoaded', detectMetaMask);
}

function detectMetaMask() {
  if (typeof window.ethereum !== 'undefined') {
    console.log('MetaMask detected!');
  } else {
    console.log('Please install MetaMask!');
    window.open('https://metamask.io/download/', '_blank');
  }
}
```

#### Network Addition Failed

```javascript
async function forceAddNetwork() {
  try {
    // Try to switch first
    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x3d8' }],
    });
  } catch (error) {
    if (error.code === 4902) {
      // Add network with retry
      let retries = 3;
      while (retries > 0) {
        try {
          await window.ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [OPN_NETWORK_CONFIG],
          });
          break;
        } catch (addError) {
          retries--;
          if (retries === 0) throw addError;
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
    }
  }
}
```

#### Mobile Connection Issues

For mobile DApps, use deep linking:

```javascript
function connectMobileWallet() {
  const dappUrl = window.location.href;
  const metamaskAppUrl = `https://metamask.app.link/dapp/${dappUrl}`;
  
  // Detect mobile
  const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
  
  if (isMobile && !window.ethereum) {
    window.location.href = metamaskAppUrl;
  }
}
```

***

**Need help?** Join our [Discord](https://discord.gg/iopn)


---

# 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://iopn.gitbook.io/iopn/developer-docs/getting-started/connect-wallet.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.
