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

# Error Handling

> Decode contract reverts, handle wallet rejections, and recover from RPC errors in Sei apps

export const RunSnippet = props => {
  const {method = 'eth_blockNumber', params = [], network = 'testnet', endpoint, label, title, description, decode = 'auto'} = props || ({});
  const ENDPOINTS = {
    testnet: 'https://evm-rpc-testnet.sei-apis.com',
    mainnet: 'https://evm-rpc.sei-apis.com'
  };
  const rpcUrl = endpoint || ENDPOINTS[network] || ENDPOINTS.testnet;
  const networkLabel = network === 'mainnet' ? 'pacific-1 · mainnet' : network === 'testnet' ? 'atlantic-2 · testnet' : network;
  const requestBody = {
    jsonrpc: '2.0',
    id: 1,
    method,
    params
  };
  const requestJson = JSON.stringify(requestBody, null, 2);
  const [phase, setPhase] = useState('idle');
  const [result, setResult] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [elapsed, setElapsed] = useState(null);
  const [copied, setCopied] = useState(false);
  const [btnHover, setBtnHover] = useState(false);
  const groupThousands = s => s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  const hexToDecimal = value => {
    if (typeof value !== 'string' || !(/^0x[0-9a-fA-F]+$/).test(value)) return null;
    if (value.length > 66) return null;
    try {
      return groupThousands(BigInt(value).toString(10));
    } catch (e) {
      return null;
    }
  };
  const run = async () => {
    setPhase('loading');
    setErrorMsg(null);
    setResult(null);
    setElapsed(null);
    const startedAt = typeof performance !== 'undefined' ? performance.now() : null;
    try {
      const response = await fetch(rpcUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });
      const data = await response.json();
      if (startedAt != null && typeof performance !== 'undefined') {
        setElapsed(Math.round(performance.now() - startedAt));
      }
      if (data && data.error) {
        setErrorMsg(data.error.message || 'RPC returned an error');
        setPhase('error');
        return;
      }
      setResult(data ? data.result : undefined);
      setPhase('success');
    } catch (err) {
      setErrorMsg(err && err.message ? err.message : 'Request failed');
      setPhase('error');
    }
  };
  const resultString = result === undefined ? 'undefined' : JSON.stringify(result, null, 2);
  const decoded = decode !== 'off' && typeof result === 'string' ? hexToDecimal(result) : null;
  const copyResult = () => {
    const flashCopied = () => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    };
    if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(resultString).then(flashCopied, () => {});
      return;
    }
    if (typeof document !== 'undefined') {
      try {
        const ta = document.createElement('textarea');
        ta.value = resultString;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        flashCopied();
      } catch (e) {}
    }
  };
  const HAIRLINE = 'rgba(128, 128, 128, 0.25)';
  const surfaceStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.08)'
  };
  const monoStyle = {
    fontFamily: 'var(--sei-font-mono)'
  };
  const codeStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.05)',
    fontFamily: 'var(--sei-font-mono)'
  };
  const cardClass = 'not-prose w-full rounded-lg border overflow-hidden my-4';
  const headerClass = 'flex items-center justify-between gap-3 px-4 py-2.5 border-b';
  const labelClass = 'text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-500';
  const preClass = 'm-0 px-4 py-3 text-sm overflow-x-auto text-neutral-700 dark:text-neutral-300';
  const buttonStyle = {
    backgroundColor: btnHover ? 'var(--sei-maroon-200)' : 'var(--sei-maroon-100)',
    color: '#ffffff',
    fontFamily: 'var(--sei-font-mono)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    fontSize: '10px',
    opacity: phase === 'loading' ? 0.7 : 1,
    cursor: phase === 'loading' ? 'default' : 'pointer'
  };
  return <div className={cardClass} style={{
    borderColor: HAIRLINE
  }}>
			<div className={headerClass} style={{
    ...surfaceStyle,
    borderBottomColor: HAIRLINE
  }}>
				<div className="flex flex-col min-w-0">
					<span className="text-sm font-medium text-neutral-900 dark:text-white truncate" style={monoStyle}>
						{title || method}
					</span>
					<span className="text-xs text-neutral-500 dark:text-neutral-500">{networkLabel}</span>
				</div>
				<button type="button" onClick={run} disabled={phase === 'loading'} onMouseEnter={() => setBtnHover(true)} onMouseLeave={() => setBtnHover(false)} className="inline-flex items-center gap-1.5 px-3 py-1.5 shrink-0 transition-colors" style={buttonStyle}>
					{phase === 'loading' ? <svg className="animate-spin h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
								<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z" />
							</svg> : <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
								<path d="M8 5v14l11-7z" />
							</svg>}
					{phase === 'loading' ? 'Running…' : label || 'Run'}
				</button>
			</div>

			{description ? <div className="px-4 pt-3 text-sm text-neutral-600 dark:text-neutral-400">{description}</div> : null}

			<div className="px-4 pt-3 pb-1">
				<span className={labelClass}>Request</span>
			</div>
			<pre className={preClass} style={codeStyle}>
				{requestJson}
			</pre>

			{phase === 'success' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="flex items-center justify-between px-4 pt-3 pb-1">
						<span className={labelClass}>Response{elapsed != null ? ` · ${elapsed} ms` : ''}</span>
						<button type="button" onClick={copyResult} className="text-xs text-neutral-500 hover:text-neutral-800 dark:text-neutral-400 dark:hover:text-neutral-200 transition-colors">
							{copied ? 'Copied' : 'Copy'}
						</button>
					</div>
					<pre className={preClass} style={codeStyle}>
						{resultString}
					</pre>
					{decoded ? <div className="px-4 pb-3 text-xs text-neutral-500 dark:text-neutral-500" style={monoStyle}>
							= {decoded} (decimal)
						</div> : null}
				</div> : null}

			{phase === 'error' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="px-4 pt-3 pb-1">
						<span className={labelClass}>Error</span>
					</div>
					<pre className={`${preClass} text-red-600 dark:text-red-400`} style={codeStyle}>
						{errorMsg}
					</pre>
				</div> : null}
		</div>;
};

# Error Handling

Most transaction failures fall into three categories: contract reverts, wallet rejections, and RPC errors. This page shows how to decode each type and respond correctly.

## Try it: see real errors

The `RunSnippet` widget surfaces whatever the RPC returns — including failures. These two calls fail on purpose so you can see the exact error shape your code has to handle, live against Sei mainnet.

<RunSnippet method="eth_call" params={[{ to: '0xcA11bde05977b3631167028862bE2a173976CA11', data: '0xdeadbeef' }, 'latest']} network="mainnet" title="A contract revert" description="Calls an unknown selector (0xdeadbeef) on Multicall3. The node rejects it with execution reverted — the same class of failure as the Contract Reverts section below." />

<RunSnippet method="eth_getBalance" params={['0x123', 'latest']} network="mainnet" title="An RPC argument error" description="A malformed address (0x123) triggers a JSON-RPC -32602 invalid argument error — distinct from a revert, and the kind of failure the RPC Errors and Retries section below handles." />

## Contract Reverts

When a transaction reverts, the error contains the revert reason if the contract provides one.

<CodeGroup>
  ```ts viem theme={"dark"}
  import { ContractFunctionRevertedError, BaseError } from 'viem';

  try {
    await client.simulateContract({
      address: TOKEN,
      abi: ERC20_ABI,
      functionName: 'transfer',
      args: ['0xRecipient', 1_000_000n],
      account,
    });
  } catch (err) {
    if (err instanceof BaseError) {
      const revert = err.walk((e) => e instanceof ContractFunctionRevertedError);
      if (revert instanceof ContractFunctionRevertedError) {
        console.error('Revert reason:', revert.data?.errorName);
        // e.g. 'ERC20InsufficientBalance'
      }
    }
  }
  ```

  ```ts ethers theme={"dark"}
  import { ethers } from 'ethers';

  try {
    await writeContract.transfer('0xRecipient', 1_000_000n);
  } catch (err: any) {
    if (err.code === 'CALL_EXCEPTION') {
      // Decode using the contract's ABI
      const decoded = writeContract.interface.parseError(err.data);
      if (decoded) {
        console.error('Revert:', decoded.name, decoded.args);
      } else {
        console.error('Unknown revert data:', err.data);
      }
    }
  }
  ```
</CodeGroup>

## Simulating Before Sending

Always simulate write calls before submitting them. Simulation runs the call against current chain state and surfaces reverts before you spend gas:

```ts viem theme={"dark"}
import { ContractFunctionRevertedError, BaseError } from 'viem';

async function safeWrite(params: Parameters<typeof walletClient.writeContract>[0]) {
  // 1. Simulate — reverts here cost no gas
  const { request } = await client.simulateContract(params);
  // 2. Execute only if simulation passes
  return walletClient.writeContract(request);
}
```

## Wallet Rejections

Users can reject signature and transaction requests. These rejections have a predictable error code:

<CodeGroup>
  ```ts viem theme={"dark"}
  import { UserRejectedRequestError } from 'viem';

  try {
    await walletClient.sendTransaction({ to: '0xRecipient', value: 1n });
  } catch (err) {
    if (err instanceof UserRejectedRequestError) {
      // User cancelled — don't show an error, just reset UI state
      console.log('User rejected the request');
    }
  }
  ```

  ```ts ethers theme={"dark"}
  try {
    await signer.sendTransaction({ to: '0xRecipient', value: 1n });
  } catch (err: any) {
    if (err.code === 4001 || err.code === 'ACTION_REJECTED') {
      console.log('User rejected the request');
    }
  }
  ```
</CodeGroup>

## Insufficient Funds

<CodeGroup>
  ```ts viem theme={"dark"}
  import { InsufficientFundsError } from 'viem';

  try {
    await walletClient.sendTransaction({ to: '0xRecipient', value: parseEther('9999') });
  } catch (err) {
    if (err instanceof InsufficientFundsError) {
      console.error('Not enough SEI for this transaction');
    }
  }
  ```

  ```ts ethers theme={"dark"}
  try {
    await wallet.sendTransaction({ to: '0xRecipient', value: ethers.parseEther('9999') });
  } catch (err: any) {
    if (err.code === 'INSUFFICIENT_FUNDS') {
      console.error('Not enough SEI for this transaction');
    }
  }
  ```
</CodeGroup>

## Classifying Any Error

A utility to handle the most common cases in one place:

```ts theme={"dark"}
import {
  BaseError,
  ContractFunctionRevertedError,
  UserRejectedRequestError,
  InsufficientFundsError,
} from 'viem';

function classifyError(err: unknown): string {
  if (err instanceof UserRejectedRequestError) return 'rejected';
  if (err instanceof InsufficientFundsError)  return 'insufficient_funds';

  if (err instanceof BaseError) {
    const revert = err.walk((e) => e instanceof ContractFunctionRevertedError);
    if (revert instanceof ContractFunctionRevertedError) {
      return `revert:${revert.data?.errorName ?? 'unknown'}`;
    }
  }

  return 'unknown';
}
```

## RPC Errors and Retries

Transient RPC failures (network timeouts, rate limits) can be retried. Don't retry on contract reverts or user rejections — those are deterministic.

```ts theme={"dark"}
async function withRetry<T>(fn: () => Promise<T>, maxAttempts = 3): Promise<T> {
  let lastError: unknown;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (err: any) {
      // Don't retry user rejections or contract reverts
      if (
        err instanceof UserRejectedRequestError ||
        err?.code === 4001 ||
        err?.code === 'CALL_EXCEPTION'
      ) {
        throw err;
      }
      lastError = err;
      if (attempt < maxAttempts) {
        await new Promise((r) => setTimeout(r, 500 * attempt)); // backoff
      }
    }
  }
  throw lastError;
}

// Usage
const balance = await withRetry(() =>
  client.readContract({ address: TOKEN, abi: ERC20_ABI, functionName: 'balanceOf', args: [owner] })
);
```
