React Hooks for Ethereum providing reactive primitives for wallet connections, smart contract interactions, and blockchain data
—
Advanced functionality including proof generation, SSR hydration, context management, and error handling. This module covers specialized wagmi features for complex applications and edge cases.
Hook to get account proof data for cryptographic verification and state proofs.
/**
* Hook to get account proof
* @param parameters - Account proof query parameters
* @returns Account proof data with storage proofs
*/
function useProof<config = Config, selectData = UseProofReturnType>(
parameters: UseProofParameters<config, selectData>
): UseProofReturnType<selectData>;
interface UseProofParameters<config = Config, selectData = UseProofReturnType> {
/** Address to generate proof for */
address: Address;
/** Storage keys to include in proof */
storageKeys: Hex[];
/** Block number to generate proof at */
blockNumber?: bigint;
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
/** Chain to use */
chainId?: config['chains'][number]['id'];
config?: Config | config;
query?: {
enabled?: boolean;
staleTime?: number;
gcTime?: number;
select?: (data: UseProofReturnType) => selectData;
};
}
interface UseProofReturnType {
/** Account address */
address: Address;
/** Account nonce */
nonce: Hex;
/** Account balance */
balance: Hex;
/** Code hash */
codeHash: Hex;
/** Storage hash */
storageHash: Hex;
/** Account proof */
accountProof: Hex[];
/** Storage proofs */
storageProof: StorageProof[];
}
interface StorageProof {
/** Storage key */
key: Hex;
/** Storage value */
value: Hex;
/** Storage proof */
proof: Hex[];
}Usage Example:
import { useProof } from "wagmi";
function AccountProofGenerator() {
const { data: proof, isLoading } = useProof({
address: '0x742d35Cc6634C0532925a3b8D',
storageKeys: [
'0x0000000000000000000000000000000000000000000000000000000000000000',
],
});
if (isLoading) return <div>Generating proof...</div>;
return (
<div>
<h3>Account Proof</h3>
<p>Address: {proof?.address}</p>
<p>Nonce: {proof?.nonce}</p>
<p>Balance: {proof?.balance}</p>
<p>Storage Proofs: {proof?.storageProof.length}</p>
<details>
<summary>Account Proof ({proof?.accountProof.length} items)</summary>
{proof?.accountProof.map((item, i) => (
<p key={i} style={{ fontSize: '0.8em', wordBreak: 'break-all' }}>
{item}
</p>
))}
</details>
</div>
);
}Main provider component that configures wagmi for your application.
/**
* Main provider component for wagmi configuration
* @param props - Provider configuration
* @returns React provider component
*/
function WagmiProvider(props: WagmiProviderProps): JSX.Element;
interface WagmiProviderProps {
/** Wagmi configuration object */
config: ResolvedRegister['config'];
/** Initial state for SSR/hydration */
initialState?: State;
/** Whether to reconnect on mount (default: true) */
reconnectOnMount?: boolean;
/** React children */
children: React.ReactNode;
}
interface ResolvedRegister {
config: Config;
}
interface Config {
/** Configured chains */
chains: readonly Chain[];
/** Available connectors */
connectors: Connector[];
/** Transport configuration */
transports: Record<number, Transport>;
/** Internal state */
state: State;
/** Storage implementation */
storage?: Storage;
/** SSR mode */
ssr?: boolean;
/** Sync connected chain */
syncConnectedChain?: boolean;
/** Multi-injected provider discovery */
multiInjectedProviderDiscovery?: boolean;
}React context for accessing wagmi configuration and state.
/**
* React context for wagmi configuration access
*/
const WagmiContext: React.Context<Config | undefined>;
/**
* Hook to access wagmi context
* @returns Wagmi configuration
* @throws WagmiProviderNotFoundError if used outside provider
*/
function useConfig(): Config;Component for handling SSR hydration with wagmi state.
/**
* Component for SSR hydration support
* @param props - Hydration configuration
* @returns React component for hydration
*/
function Hydrate(props: HydrateProps): JSX.Element;
interface HydrateProps {
/** Wagmi configuration */
config: ResolvedRegister['config'];
/** Initial state for hydration */
initialState?: State;
/** Whether to reconnect on mount */
reconnectOnMount?: boolean;
/** React children */
children: React.ReactNode;
}Usage Example:
import { Hydrate, WagmiProvider } from "wagmi";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Server-side
function getInitialState() {
// Return serialized wagmi state from server
return {
chainId: 1,
connections: new Map(),
current: undefined,
status: 'disconnected' as const,
};
}
// Client-side
function App({ initialState }: { initialState?: State }) {
const queryClient = new QueryClient();
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<Hydrate initialState={initialState}>
<MyApp />
</Hydrate>
</QueryClientProvider>
</WagmiProvider>
);
}Error thrown when wagmi hooks are used outside of WagmiProvider context.
/**
* Error thrown when WagmiProvider context is not found
*/
class WagmiProviderNotFoundError extends BaseError {
name: 'WagmiProviderNotFoundError';
constructor();
}
/**
* Type for WagmiProviderNotFoundError
*/
type WagmiProviderNotFoundErrorType = WagmiProviderNotFoundError;Base error class for all wagmi React errors.
/**
* Base error class for wagmi React errors
*/
class BaseError extends Error {
name: 'BaseError';
constructor(shortMessage: string, args?: BaseErrorParameters);
}
interface BaseErrorParameters {
cause?: unknown;
details?: string;
docsPath?: string;
metaMessages?: string[];
}
/**
* Type for BaseError
*/
type BaseErrorType = BaseError;Error Handling Example:
import { useAccount, WagmiProviderNotFoundError } from "wagmi";
function ErrorBoundaryComponent() {
try {
const { address } = useAccount();
return <div>Address: {address}</div>;
} catch (error) {
if (error instanceof WagmiProviderNotFoundError) {
return (
<div>
Error: Wagmi hooks must be used within WagmiProvider.
Please wrap your component with WagmiProvider.
</div>
);
}
throw error; // Re-throw other errors
}
}Hook to get the connector's client instance for direct interaction.
/**
* Hook to get connector's client
* @param parameters - Connector client parameters
* @returns Connector client instance
*/
function useConnectorClient<config = Config>(
parameters?: UseConnectorClientParameters<config>
): UseConnectorClientReturnType<config>;
interface UseConnectorClientParameters<config = Config> {
/** Specific connector to get client for */
connector?: Connector;
/** Chain ID for the client */
chainId?: config['chains'][number]['id'];
config?: Config | config;
query?: {
enabled?: boolean;
staleTime?: number;
gcTime?: number;
};
}
type UseConnectorClientReturnType<config = Config> = {
data?: ConnectorClient;
error: Error | null;
isError: boolean;
isLoading: boolean;
isSuccess: boolean;
status: 'error' | 'loading' | 'success';
};
interface ConnectorClient {
/** Client instance */
client: Client;
/** Transport configuration */
transport: Transport;
/** Account information */
account?: Account;
/** Chain information */
chain?: Chain;
}Hook to get a wallet client for signing operations.
/**
* Hook to get wallet client for signing
* @param parameters - Wallet client parameters
* @returns Wallet client instance
*/
function useWalletClient<config = Config, selectData = UseWalletClientReturnType>(
parameters?: UseWalletClientParameters<config, selectData>
): UseWalletClientReturnType<selectData>;
interface UseWalletClientParameters<config = Config, selectData = UseWalletClientReturnType> {
/** Account to get wallet client for */
account?: Address;
/** Chain ID */
chainId?: config['chains'][number]['id'];
config?: Config | config;
query?: {
enabled?: boolean;
staleTime?: number;
gcTime?: number;
select?: (data: UseWalletClientReturnType) => selectData;
};
}
type UseWalletClientReturnType = WalletClient | undefined;
interface WalletClient extends Client {
/** Account for wallet operations */
account: Account;
/** Request permissions */
requestPermissions?: (permissions: Permission[]) => Promise<Permission[]>;
/** Get permissions */
getPermissions?: () => Promise<Permission[]>;
/** Switch chain */
switchChain?: (args: { id: number }) => Promise<void>;
/** Watch asset */
watchAsset?: (asset: WatchAssetParams) => Promise<boolean>;
}Function to create wagmi configuration with type safety.
/**
* Create wagmi configuration
* @param parameters - Configuration parameters
* @returns Configured wagmi config
*/
function createConfig(parameters: CreateConfigParameters): Config;
interface CreateConfigParameters {
/** Supported chains */
chains: readonly [Chain, ...Chain[]];
/** Available connectors */
connectors?: Connector[];
/** Transport configuration per chain */
transports: Record<number, Transport>;
/** Storage implementation */
storage?: Storage;
/** SSR support */
ssr?: boolean;
/** Sync connected chain */
syncConnectedChain?: boolean;
/** Enable multi-injected provider discovery */
multiInjectedProviderDiscovery?: boolean;
}/**
* Storage interface for wagmi state persistence
*/
interface Storage {
getItem: (key: string) => string | null | Promise<string | null>;
setItem: (key: string, value: string) => void | Promise<void>;
removeItem: (key: string) => void | Promise<void>;
}
/**
* Create custom storage implementation
* @param parameters - Storage parameters
* @returns Storage implementation
*/
function createStorage(parameters: CreateStorageParameters): Storage;
interface CreateStorageParameters {
/** Storage key prefix */
key?: string;
/** Storage implementation */
storage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
/** Serialization functions */
serialize?: (value: unknown) => string;
deserialize?: (value: string) => unknown;
}
/**
* No-op storage (doesn't persist anything)
*/
const noopStorage: Storage;
/**
* Cookie-based storage for SSR
*/
const cookieStorage: Storage;import { useAccount, BaseError } from "wagmi";
import { useErrorBoundary } from "react-error-boundary";
function useAccountWithErrorHandling() {
const { showBoundary } = useErrorBoundary();
try {
return useAccount();
} catch (error) {
if (error instanceof BaseError) {
showBoundary(error);
}
throw error;
}
}import { cookieToInitialState, parseCookie } from "wagmi";
// Server-side state extraction
function getServerSideWagmiState(cookieHeader?: string) {
if (!cookieHeader) return undefined;
const cookie = parseCookie(cookieHeader, 'wagmi.store');
return cookieToInitialState(config, cookie);
}
// Next.js example
export async function getServerSideProps(context: GetServerSidePropsContext) {
return {
props: {
initialWagmiState: getServerSideWagmiState(context.req.headers.cookie),
},
};
}type Address = `0x${string}`;
type Hash = `0x${string}`;
type Hex = `0x${string}`;
interface State {
chainId: number;
connections: Map<string, Connection>;
current?: string;
status: 'connecting' | 'connected' | 'disconnected' | 'reconnecting';
}
interface Connection {
accounts: readonly Address[];
chainId: number;
connector: Connector;
}
interface Chain {
id: number;
name: string;
network: string;
nativeCurrency: {
name: string;
symbol: string;
decimals: number;
};
rpcUrls: {
default: { http: readonly string[] };
public: { http: readonly string[] };
};
blockExplorers?: {
default: { name: string; url: string };
};
}
interface Connector {
id: string;
name: string;
type: string;
icon?: string;
ready?: boolean;
}
interface Transport {
key: string;
name: string;
request: (request: { method: string; params?: any[] }) => Promise<any>;
type: string;
}
interface Account {
address: Address;
type: 'json-rpc' | 'local' | 'privateKey';
}
interface Permission {
caveats: Caveat[];
date: number;
id: string;
invoker: string;
parentCapability: string;
}
interface Caveat {
type: string;
value: unknown;
}
interface WatchAssetParams {
type: 'ERC20';
options: {
address: Address;
symbol?: string;
decimals?: number;
image?: string;
};
}Install with Tessl CLI
npx tessl i tessl/npm-wagmi