# MetaMask Integration Guide

Complete guide for integrating ChainID 138 (DeFi Oracle Meta Mainnet) with MetaMask.

## Overview

This guide covers how to add ChainID 138 to MetaMask, add tokens, and integrate wallet functionality into your dapp.

## Network Information

- **ChainID**: 138 (0x8a in hex)
- **Chain Name**: DeFi Oracle Meta Mainnet
- **Native Currency**: ETH (18 decimals)
- **RPC URLs**:
  - Primary: `https://rpc.d-bis.org`
  - Secondary: `https://rpc2.d-bis.org`
  - WebSocket: `wss://rpc.d-bis.org`
- **Block Explorer**: `https://explorer.d-bis.org`
- **Domain**: `d-bis.org` (Cloudflare DNS/SSL)

## Adding the Network

### Option 1: Using the MetaMask SDK

```typescript
import { addOrSwitchNetwork } from '@defi-oracle/metamask-sdk';

// Add or switch to ChainID 138
await addOrSwitchNetwork();
```

### Option 2: Using wallet_addEthereumChain

```javascript
await window.ethereum.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x8a',
    chainName: 'DeFi Oracle Meta Mainnet',
    nativeCurrency: {
      name: 'Ether',
      symbol: 'ETH',
      decimals: 18
    },
    rpcUrls: ['https://rpc.d-bis.org', 'https://rpc2.d-bis.org'],
    blockExplorerUrls: ['https://explorer.d-bis.org'],
    iconUrls: ['https://explorer.d-bis.org/images/logo.png']
  }]
});
```

### Option 3: Using Chainlist

1. Visit [chainlist.org](https://chainlist.org)
2. Search for "ChainID 138" or "DeFi Oracle Meta"
3. Click "Add to MetaMask"
4. Approve the network addition in MetaMask

### Option 4: Manual Addition

1. Open MetaMask
2. Click the network dropdown
3. Click "Add Network"
4. Click "Add a network manually"
5. Enter the network details:
   - Network Name: DeFi Oracle Meta Mainnet
   - RPC URL: `https://rpc.d-bis.org`
   - Chain ID: 138
   - Currency Symbol: ETH
   - Block Explorer URL: `https://explorer.d-bis.org`

## Switching Networks

```javascript
await window.ethereum.request({
  method: 'wallet_switchEthereumChain',
  params: [{ chainId: '0x8a' }]
});
```

## Adding Tokens

### Using the SDK

```typescript
import { addToken } from '@defi-oracle/metamask-sdk';

await addToken(
  '0xYourTokenAddress',
  'WETH',
  18,
  'https://explorer.d-bis.org/images/tokens/weth.png'
);
```

### Using wallet_watchAsset (EIP-747)

```javascript
await window.ethereum.request({
  method: 'wallet_watchAsset',
  params: {
    type: 'ERC20',
    options: {
      address: '0xYourTokenAddress',
      symbol: 'WETH',
      decimals: 18,
      image: 'https://explorer.d-bis.org/images/tokens/weth.png'
    }
  }
});
```

## Checking Current Network

```javascript
const chainId = await window.ethereum.request({ method: 'eth_chainId' });
if (chainId === '0x8a') {
  console.log('Connected to ChainID 138');
}
```

## Listening to Network Changes

```javascript
window.ethereum.on('chainChanged', (chainId) => {
  if (chainId === '0x8a') {
    console.log('Switched to ChainID 138');
  } else {
    console.log('Switched to another network');
  }
});
```

## Complete Integration Example

```javascript
async function connectToChain138() {
  // Check if MetaMask is installed
  if (typeof window.ethereum === 'undefined') {
    alert('Please install MetaMask');
    return;
  }

  try {
    // Get current chain ID
    const chainId = await window.ethereum.request({ method: 'eth_chainId' });

    // If not on ChainID 138, switch or add
    if (chainId !== '0x8a') {
      try {
        // Try to switch first
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: '0x8a' }]
        });
      } catch (error) {
        // If switch fails, network might not be added
        if (error.code === 4902) {
          // Add the network
          await window.ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [{
              chainId: '0x8a',
              chainName: 'DeFi Oracle Meta Mainnet',
              nativeCurrency: {
                name: 'Ether',
                symbol: 'ETH',
                decimals: 18
              },
              rpcUrls: ['https://rpc.d-bis.org'],
              blockExplorerUrls: ['https://explorer.d-bis.org']
            }]
          });
        } else {
          throw error;
        }
      }
    }

    console.log('Connected to ChainID 138');
  } catch (error) {
    console.error('Error connecting to ChainID 138:', error);
  }
}
```

## Token List

See the official token list at: `metamask/token-list.json`

Tokens are automatically detected by MetaMask when they appear on 2+ reputable token lists. To enable auto-detection:

1. Add your token to the official token list
2. Submit the token list to reputable aggregators (CoinGecko, etc.)
3. Ensure token metadata is available on Blockscout

## Troubleshooting

### MetaMask not detected

```javascript
if (typeof window.ethereum === 'undefined') {
  alert('Please install MetaMask');
  window.open('https://metamask.io/download/', '_blank');
}
```

### Network already added

If you get an error that the network is already added, use `wallet_switchEthereumChain` instead.

### RPC endpoint errors

- Verify RPC URL is correct: `https://rpc.d-bis.org`
- Check network connectivity
- Verify RPC node is running and accessible
- Check firewall/security settings

### Token not showing

- Verify token address is correct
- Check token contract is deployed on ChainID 138
- Verify token metadata (symbol, decimals) is correct
- Ensure token logo URL is accessible

## Security Best Practices

1. **Verify RPC URLs**: Always use the official RPC URLs from this documentation
2. **Verify Explorer URLs**: Use the official Blockscout explorer
3. **Verify Token Addresses**: Double-check token contract addresses before adding
4. **Avoid Phishing**: Only add networks from trusted sources
5. **Check Domain**: Verify you're on the official domain (d-bis.org)

## References

- [MetaMask Documentation](https://docs.metamask.io)
- [EIP-3085: wallet_addEthereumChain](https://eips.ethereum.org/EIPS/eip-3085)
- [EIP-747: wallet_watchAsset](https://eips.ethereum.org/EIPS/eip-747)
- [Chainlist](https://chainlist.org)
- [Blockscout Explorer](https://explorer.d-bis.org)

