Wallet Integration Guide for dApp Developers

How to connect wallets to a dApp using EIP-1193 and EIP-6963, handle accounts and networks, sign messages and choose between viem, ethers and AppKit.

In this guide
  1. How a dApp talks to a wallet
  2. Discover wallets with EIP-6963
  3. Connect and track the account
  4. Handle networks
  5. Sign messages and send transactions
  6. Mobile and remote wallets with Reown AppKit
  7. UX and security checklist
  8. FAQ
  9. Sources

Integrating a wallet on EVM chains comes down to three standards-based steps: discover the wallets a user has installed with EIP-6963, talk to the chosen one through its EIP-1193 provider, and react to account and network changes. For mobile and remote wallets you add a relay-based connection, most commonly through Reown AppKit (the toolkit formerly known as Web3Modal, from the company previously called WalletConnect Inc.).

The code here is framework-neutral TypeScript, checked against viem 2.x and ethers 6.17.

How a dApp talks to a wallet

A wallet never hands your page a private key. It exposes a provider object, and your code sends it JSON-RPC requests. The wallet decides whether to answer directly, show the user a prompt, or refuse. EIP-1193, a finalized Ethereum standard, defines that object.

The whole interface is one method, request({ method, params }), which returns a promise, plus on and removeListener for events.

Events you should handle:

Event Payload What to do
accountsChanged Array of addresses Update the active account; an empty array means disconnected
chainChanged Chain ID as a hex string Update network state and refetch chain-specific data
disconnect Error object Provider lost connection to all chains; offer to reconnect

Rejections arrive as errors with a numeric code:

Code Meaning Sensible handling
4001 User rejected the request Not a failure; return quietly to the previous state
4100 Method or account not authorized Ask the user to connect first
4200 Method not supported by this provider Hide or disable the feature
4900 / 4901 Provider disconnected from all chains / from the requested chain Prompt to reconnect or switch network

Libraries such as viem and ethers wrap this provider with typed helpers, but every call still passes through request(). Knowing the raw layer makes debugging easier and is a common topic in blockchain developer interview questions.

Discover wallets with EIP-6963

For years, wallets injected themselves at window.ethereum. With two extensions installed, whichever loaded last won, and users could not choose. EIP-6963, also final, replaces the shared global with an event handshake:

  • each wallet dispatches eip6963:announceProvider on window, carrying its name, icon, a unique ID and its EIP-1193 provider;
  • the dApp dispatches eip6963:requestProvider to ask wallets to announce again, which covers wallets that loaded before the page started listening.
import type { EIP1193Provider } from 'viem';

interface EIP6963ProviderInfo {
  uuid: string; // UUIDv4 identifying this provider
  name: string; // human-readable wallet name
  icon: string; // data URI
  rdns: string; // reverse-DNS identifier of the wallet
}

export interface EIP6963ProviderDetail {
  info: EIP6963ProviderInfo;
  provider: EIP1193Provider;
}

export function discoverWallets(
  onChange: (wallets: EIP6963ProviderDetail[]) => void,
): () => void {
  const found = new Map<string, EIP6963ProviderDetail>();

  const onAnnounce = (event: Event) => {
    const { detail } = event as CustomEvent<EIP6963ProviderDetail>;
    found.set(detail.info.uuid, detail);
    onChange([...found.values()]);
  };

  window.addEventListener('eip6963:announceProvider', onAnnounce);
  window.dispatchEvent(new Event('eip6963:requestProvider'));

  return () =>
    window.removeEventListener('eip6963:announceProvider', onAnnounce);
}

Render the list as buttons using each wallet's name and icon. Treat name and icon as untrusted input: render the name as text and the icon only through an <img> element. Keep window.ethereum as a fallback for older wallets that do not announce themselves.

Sequence between a dApp and a wallet: the dApp dispatches eip6963:requestProvider, the wallet answers with eip6963:announceProvider, then the dApp calls provider.request, the wallet may prompt the user and returns a result or an error such as 4001.
Discovery happens once per page load; every later call goes through the provider's request method.

Connect and track the account

Two RPC methods look similar and behave differently:

  • eth_requestAccounts opens the wallet's permission prompt. Call it only in response to a click.
  • eth_accounts returns accounts the user has already authorized, without a prompt. Call it on page load to restore a session silently.

With viem these are requestAddresses() and getAddresses() on a wallet client. The connect path looks like this; to restore a session, build the same client and call getAddresses() instead.

import { createWalletClient, custom, type Address, type EIP1193Provider } from 'viem';
import { sepolia } from 'viem/chains';

export async function connect(provider: EIP1193Provider) {
  const walletClient = createWalletClient({
    chain: sepolia,
    transport: custom(provider),
  });

  let address: Address | undefined;
  try {
    [address] = await walletClient.requestAddresses();
  } catch (err) {
    if ((err as { code?: number }).code === 4001) return null; // user declined
    throw err;
  }
  if (!address) return null;

  provider.on('accountsChanged', (accounts) => {
    // Re-run your "account changed" logic with accounts[0], or disconnect if empty.
  });
  provider.on('chainChanged', (chainIdHex) => {
    // Number(chainIdHex) is the new chain ID.
  });

  return { walletClient, address };
}

The equivalent with ethers v6:

import { BrowserProvider } from 'ethers';

const browserProvider = new BrowserProvider(provider);
const signer = await browserProvider.getSigner(); // prompts if needed
const address = await signer.getAddress();

EIP-1193 defines no "disconnect" request. A disconnect button normally just clears your application's own state.

Our Angular dApp front end guide shows how to hold this state in a signal-based service.

Handle networks

A user's wallet may be on a different chain from your contracts. Compare the wallet's chain ID with the one you expect and offer a switch instead of letting a transaction fail.

Switching uses wallet_switchEthereumChain. If the wallet does not know the chain, MetaMask documents error code 4902 and recommends adding the chain with wallet_addEthereumChain:

import { numberToHex, type Chain, type EIP1193Provider } from 'viem';

export async function ensureChain(provider: EIP1193Provider, chain: Chain) {
  const chainId = numberToHex(chain.id);
  try {
    await provider.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId }],
    });
  } catch (err) {
    if ((err as { code?: number }).code !== 4902) throw err;

    await provider.request({
      method: 'wallet_addEthereumChain',
      params: [
        {
          chainId,
          chainName: chain.name,
          nativeCurrency: chain.nativeCurrency,
          rpcUrls: [...chain.rpcUrls.default.http],
          blockExplorerUrls: chain.blockExplorers
            ? [chain.blockExplorers.default.url]
            : undefined,
        },
      ],
    });
  }
}

Chain IDs in these RPC calls are hexadecimal strings, not numbers.

This matters most when your dApp lives on a rollup that users may not have configured yet; see Layer 2 explained for developers. Do reads through your own RPC endpoint rather than through the wallet, so the page can show data before anyone connects.

Sign messages and send transactions

Signing in

A connected address is only a claim. To authenticate a user to your backend, have them sign a message:

  1. The server issues a random, single-use nonce.
  2. The client asks the wallet to sign a human-readable message containing the nonce, your domain and the chain ID.
  3. The server verifies the signature against the claimed address, checks and consumes the nonce, then creates a session.
// Client
const signature = await walletClient.signMessage({ account: address, message });

// Server (viem public client)
const valid = await publicClient.verifyMessage({ address, message, signature });

Signing a message costs no gas and sends no transaction. Once the user is authenticated, off-chain data such as profiles can live in a regular database, as described in off-chain data with PostgreSQL.

Sending transactions

For contract writes, simulate first and then send, a pattern viem's documentation recommends because writeContract on its own does not check whether the call will succeed:

const { request } = await publicClient.simulateContract({
  account: address,
  address: contractAddress,
  abi,
  functionName: 'increment',
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });

Show each stage in the interface: waiting for the wallet, submitted, confirmed or failed.

Mobile and remote wallets with Reown AppKit

Injected providers only cover browser extensions and in-wallet browsers. Reaching a wallet app on another device needs a remote connection, typically started by scanning a QR code. WalletConnect is the widely adopted way to do this.

The naming changed in 2024 and still causes confusion:

  • The company WalletConnect Inc. rebranded as Reown. The WalletConnect Network kept its name.
  • AppKit is Reown's SDK for dApps and replaces Web3Modal. @web3modal/* packages became @reown/appkit-*.
  • WalletKit is the SDK for wallet developers and replaces @walletconnect/web3wallet.
  • The old packages reached end of life in February 2025. Tutorials that install @web3modal/... are outdated.

A minimal setup with the JavaScript package and its Wagmi adapter:

npm install @reown/appkit @reown/appkit-adapter-wagmi wagmi viem @wagmi/connectors
import { createAppKit } from '@reown/appkit';
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi';
import { mainnet, arbitrum } from '@reown/appkit/networks';

const projectId = 'YOUR_PROJECT_ID'; // from the Reown Dashboard
const networks = [mainnet, arbitrum];

const modal = createAppKit({
  adapters: [new WagmiAdapter({ projectId, networks })],
  networks,
  projectId,
  metadata: {
    name: 'My dApp',
    description: 'Example dApp',
    url: 'https://example.com', // must match the domain you deploy on
    icons: ['https://example.com/icon.png'],
  },
});

document
  .querySelector('#connect')
  ?.addEventListener('click', () => modal.open());

A project ID from the Reown Dashboard is required. AppKit renders the connection modal and also offers email and social sign-in.

Which approach to use

Approach You get You give up
Raw EIP-1193 and EIP-6963 No dependencies, full control, best for learning You write every edge case; extensions only
viem or ethers on top of the provider Typed calls, ABI encoding, error classes Still no remote wallets or built-in UI
@wagmi/core Connectors, reconnection and multi-wallet state on top of viem More concepts and configuration
Reown AppKit Complete connection UI, QR and mobile linking, many wallets External service, project ID, larger bundle

UX and security checklist

  • Never ask for a seed phrase or private key. No legitimate dApp needs one.
  • Do not prompt on page load. Request accounts only after the user clicks a connect button.
  • Treat code 4001 as a normal outcome. A user who cancels does not need a red error banner.
  • Make signing requests readable. Explain what a signature or transaction will do before the wallet prompt appears.
  • Keep token approvals narrow. Request the amount the action needs. Unlimited approvals turn any later contract bug into a loss of user funds; see smart contract security basics.
  • Handle account and chain changes mid-flow. Cancel or restart pending steps when either event fires.
  • Test with more than one wallet, including a profile with no wallet and one with two extensions. Other ecosystems such as Solana use different wallet interfaces; see Solidity vs Rust.

FAQ

Is window.ethereum deprecated?

It is not removed, and many wallets still set it. But it cannot represent more than one wallet reliably. Use EIP-6963 discovery as the primary method and keep window.ethereum as a fallback.

Is WalletConnect the same thing as Reown?

Reown is the new name of the company formerly called WalletConnect Inc. The WalletConnect Network keeps its name, and Reown's AppKit and WalletKit are the SDKs that developers install today.

Should I use viem or ethers?

Both are maintained and both work on top of any EIP-1193 provider. viem offers strong type inference from ABIs and is the foundation of wagmi and AppKit's Wagmi adapter. ethers v6 has a compact, class-based API that many existing codebases and tutorials use. Choose the one your team and dependencies already favor.

Sources

About the author

Alessandro Moretti is a crypto analyst and blockchain strategist who writes and maintains the guides on BlockDev Path. Every factual claim is checked against the primary sources listed above. Spotted an error? Tell us and we will correct it. See our editorial policy.