> ## Documentation Index
> Fetch the complete documentation index at: https://docs.streambird.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Ethereum Provider

Access your embedded wallet's EIP-1193 provider to integrate with popular Web3 libraries like viem, ethers, and wagmi.

## Overview

All MoonKey embedded wallets expose a standard [EIP-1193 provider](https://eips.ethereum.org/EIPS/eip-1193) that enables you to:

* Send JSON-RPC requests directly to the wallet
* Integrate with Web3 libraries (viem, ethers, wagmi)
* Use familiar Ethereum API methods

<Info>
  [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) is the standardized Ethereum JavaScript API for how applications request information, signatures, and transactions from wallets.
</Info>

## Getting the Provider

To get a wallet's EIP-1193 provider, use the `getEthereumProvider()` method:

```tsx theme={null}
import { useMoonKey } from '@moon-key/react-auth';
import { useWallets } from '@moon-key/react-auth/ethereum';

function MyComponent() {
  const { user } = useMoonKey();
  const { wallets } = useWallets();

  const getProvider = async () => {
    if (wallets.length === 0) return;

    const wallet = wallets[0];
    const provider = await wallet.getEthereumProvider();
    
    console.log('Provider:', provider);
    return provider;
  };

  return (
    <button onClick={getProvider}>
      Get Provider
    </button>
  );
}
```

## Using with Web3 Libraries

### With Viem

```tsx theme={null}
import { useMoonKey } from '@moon-key/react-auth';
import { useWallets } from '@moon-key/react-auth/ethereum';
import { createWalletClient, custom } from 'viem';
import { mainnet } from 'viem/chains';

function ViemIntegration() {
  const { user } = useMoonKey();
  const { wallets } = useWallets();

  const sendWithViem = async () => {
    if (wallets.length === 0) return;

    const wallet = wallets[0];
    const provider = await wallet.getEthereumProvider();

    // Create viem wallet client
    const walletClient = createWalletClient({
      account: wallet.address as `0x${string}`,
      chain: mainnet,
      transport: custom(provider)
    });

    // Send transaction using viem
    const hash = await walletClient.sendTransaction({
      to: '0xRecipientAddress...',
      value: 1000000000000000n // 0.001 ETH
    });

    console.log('Transaction hash:', hash);
  };

  return (
    <button onClick={sendWithViem}>
      Send with Viem
    </button>
  );
}
```

### With Ethers

```tsx theme={null}
import { useMoonKey } from '@moon-key/react-auth';
import { useWallets } from '@moon-key/react-auth/ethereum';
import { BrowserProvider } from 'ethers';

function EthersIntegration() {
  const { user } = useMoonKey();
  const { wallets } = useWallets();

  const sendWithEthers = async () => {
    if (wallets.length === 0) return;

    const wallet = wallets[0];
    const provider = await wallet.getEthereumProvider();

    // Create ethers provider
    const ethersProvider = new BrowserProvider(provider);
    const signer = await ethersProvider.getSigner();

    // Send transaction using ethers
    const tx = await signer.sendTransaction({
      to: '0xRecipientAddress...',
      value: '1000000000000000' // 0.001 ETH in wei
    });

    await tx.wait();
    console.log('Transaction hash:', tx.hash);
  };

  return (
    <button onClick={sendWithEthers}>
      Send with Ethers
    </button>
  );
}
```

## Direct JSON-RPC Requests

You can also send JSON-RPC requests directly to the provider:

```tsx theme={null}
import { useMoonKey } from '@moon-key/react-auth';
import { useWallets } from '@moon-key/react-auth/ethereum';

function DirectRPCExample() {
  const { user } = useMoonKey();
  const { wallets } = useWallets();

  const getBalance = async () => {
    if (wallets.length === 0) return;

    const wallet = wallets[0];
    const provider = await wallet.getEthereumProvider();

    // Get balance using eth_getBalance
    const balance = await provider.request({
      method: 'eth_getBalance',
      params: [wallet.address, 'latest']
    });

    console.log('Balance (wei):', balance);
  };

  const signMessage = async () => {
    if (wallets.length === 0) return;

    const wallet = wallets[0];
    const provider = await wallet.getEthereumProvider();

    // Sign message using personal_sign
    const signature = await provider.request({
      method: 'personal_sign',
      params: ['Hello from MoonKey!', wallet.address]
    });

    console.log('Signature:', signature);
  };

  return (
    <div>
      <button onClick={getBalance}>Get Balance</button>
      <button onClick={signMessage}>Sign Message</button>
    </div>
  );
}
```

## Common JSON-RPC Methods

The provider supports standard Ethereum JSON-RPC methods:

| Method                       | Description               |
| ---------------------------- | ------------------------- |
| `eth_accounts`               | Get wallet addresses      |
| `eth_chainId`                | Get current chain ID      |
| `eth_getBalance`             | Get wallet balance        |
| `eth_sendTransaction`        | Send a transaction        |
| `eth_signTransaction`        | Sign a transaction        |
| `personal_sign`              | Sign a message            |
| `eth_signTypedData_v4`       | Sign typed data (EIP-712) |
| `wallet_switchEthereumChain` | Switch network            |

## When to Use the Provider

Use the EIP-1193 provider when you need to:

* **Integrate with existing Web3 libraries** (viem, ethers, wagmi)
* **Send custom JSON-RPC requests** not covered by MoonKey's SDK
* **Use library-specific features** (e.g., viem's contract interactions)
* **Migrate from other wallet providers** with minimal code changes

<Tip>
  For common operations like sending transactions or signing messages, consider using MoonKey's native hooks (`useSendTransaction`, `useSignMessage`) for better UI customization and error handling.
</Tip>

## Complete Example

Here's a complete example showing provider usage with viem for contract interaction:

```tsx theme={null}
'use client';
import { useMoonKey } from '@moon-key/react-auth';
import { useWallets } from '@moon-key/react-auth/ethereum';
import { createWalletClient, custom, parseAbi } from 'viem';
import { mainnet } from 'viem/chains';

const ERC20_ABI = parseAbi([
  'function transfer(address to, uint256 amount) returns (bool)',
  'function balanceOf(address account) view returns (uint256)'
]);

export default function ContractInteraction() {
  const { user } = useMoonKey();
  const { wallets } = useWallets();

  const transferTokens = async () => {
    if (wallets.length === 0) {
      alert('No wallet found');
      return;
    }

    const wallet = wallets[0];
    const provider = await wallet.getEthereumProvider();

    // Create viem client
    const walletClient = createWalletClient({
      account: wallet.address as `0x${string}`,
      chain: mainnet,
      transport: custom(provider)
    });

    try {
      // Call contract method
      const hash = await walletClient.writeContract({
        address: '0xTokenContractAddress...',
        abi: ERC20_ABI,
        functionName: 'transfer',
        args: ['0xRecipientAddress...', 1000000n] // Transfer amount
      });

      console.log('Transfer successful:', hash);
      alert(`Transfer successful! Tx: ${hash}`);
    } catch (error) {
      console.error('Transfer failed:', error);
      alert('Transfer failed');
    }
  };

  return (
    <div>
      <h2>ERC-20 Token Transfer</h2>
      <button onClick={transferTokens}>
        Transfer Tokens
      </button>
    </div>
  );
}
```

## Related Documentation

<CardGroup cols={2}>
  <Card title="Send Transaction" icon="paper-plane" href="/wallet-as-a-service/using-wallets/ethereum/send-transaction">
    Use MoonKey's native transaction sending
  </Card>

  <Card title="Sign Message" icon="signature" href="/wallet-as-a-service/using-wallets/ethereum/sign-message">
    Use MoonKey's native message signing
  </Card>

  <Card title="EIP-1193 Specification" icon="book" href="https://eips.ethereum.org/EIPS/eip-1193">
    Official EIP-1193 documentation
  </Card>

  <Card title="Viem Documentation" icon="code" href="https://viem.sh">
    Learn more about viem
  </Card>
</CardGroup>

## Next Steps

* Learn about [viem wallet clients](https://viem.sh/docs/clients/wallet) for advanced usage
* Explore [ethers.js providers](https://docs.ethers.org/v6/api/providers/) and signers
* Understand [JSON-RPC methods](https://ethereum.org/en/developers/docs/apis/json-rpc/) available on Ethereum
