VanillaJS library for Ethereum blockchain interactions with reactive primitives and utilities for building Ethereum applications
—
Wallet connection, disconnection, and network switching functionality. Handles wallet lifecycle and chain management.
Establishes connection to a wallet connector.
/**
* Connects to a wallet connector
* @param config - Wagmi configuration
* @param parameters - Connection parameters
* @returns Connection result with accounts and chain ID
*/
function connect<config extends Config, connector extends Connector | CreateConnectorFn>(
config: config,
parameters: ConnectParameters<config, connector>
): Promise<ConnectReturnType<config>>;
interface ConnectParameters<config extends Config, connector extends Connector | CreateConnectorFn> {
/** Connector to connect with */
connector: connector | CreateConnectorFn;
/** Target chain ID to connect to */
chainId?: config['chains'][number]['id'];
}
interface ConnectReturnType<config extends Config> {
/** Connected accounts */
accounts: readonly [Address, ...Address[]];
/** Connected chain ID */
chainId: config['chains'][number]['id'];
}
type ConnectErrorType =
| BaseErrorType
| ConnectorAlreadyConnectedErrorType
| ResourceUnavailableRpcErrorType
| UserRejectedRequestErrorType;Usage Example:
import { connect } from '@wagmi/core'
import { injected } from '@wagmi/core/connectors'
try {
const result = await connect(config, {
connector: injected(),
chainId: mainnet.id, // Optional: specific chain
})
console.log('Connected accounts:', result.accounts)
console.log('Connected to chain:', result.chainId)
} catch (error) {
if (error.name === 'UserRejectedRequestError') {
console.log('User rejected connection')
}
}Disconnects from the current wallet connector.
/**
* Disconnects from current connector
* @param config - Wagmi configuration
* @param parameters - Disconnect parameters (optional)
* @returns Disconnect confirmation
*/
function disconnect(
config: Config,
parameters?: DisconnectParameters
): Promise<DisconnectReturnType>;
interface DisconnectParameters {
/** Specific connector to disconnect (optional) */
connector?: Connector;
}
interface DisconnectReturnType {
/** Success confirmation */
success: true;
}
type DisconnectErrorType = BaseErrorType;Usage Example:
import { disconnect } from '@wagmi/core'
try {
await disconnect(config)
console.log('Disconnected successfully')
} catch (error) {
console.error('Disconnect failed:', error)
}Attempts to reconnect to previously connected wallets.
/**
* Reconnects to previous connectors from storage
* @param config - Wagmi configuration
* @param parameters - Reconnect parameters (optional)
* @returns Reconnection results
*/
function reconnect(
config: Config,
parameters?: ReconnectParameters
): Promise<ReconnectReturnType>;
interface ReconnectParameters {
/** Specific connectors to reconnect to */
connectors?: Connector[];
}
interface ReconnectReturnType {
/** Reconnected accounts */
accounts: readonly Address[];
/** Reconnected chain ID */
chainId: number;
}
type ReconnectErrorType = BaseErrorType;Usage Example:
import { reconnect } from '@wagmi/core'
// Typically called on app initialization
try {
const result = await reconnect(config)
if (result.accounts.length > 0) {
console.log('Reconnected to:', result.accounts)
}
} catch (error) {
console.log('No previous connection to restore')
}Switches the connected wallet to a different blockchain network.
/**
* Switches to a different blockchain network
* @param config - Wagmi configuration
* @param parameters - Switch chain parameters
* @returns Switch result with new chain info
*/
function switchChain<config extends Config>(
config: config,
parameters: SwitchChainParameters<config>
): Promise<SwitchChainReturnType<config>>;
interface SwitchChainParameters<config extends Config> {
/** Target chain ID to switch to */
chainId: config['chains'][number]['id'];
/** Specific connector to switch (optional) */
connector?: Connector;
}
interface SwitchChainReturnType<config extends Config> {
/** New chain ID */
chainId: config['chains'][number]['id'];
}
type SwitchChainErrorType =
| BaseErrorType
| SwitchChainNotSupportedErrorType
| UserRejectedRequestErrorType;
/** @deprecated Use switchChain instead */
const switchNetwork = switchChain;Usage Example:
import { switchChain } from '@wagmi/core'
import { polygon } from '@wagmi/core/chains'
try {
const result = await switchChain(config, {
chainId: polygon.id,
})
console.log('Switched to chain:', result.chainId)
} catch (error) {
if (error.name === 'SwitchChainNotSupportedError') {
console.log('Wallet does not support chain switching')
} else if (error.name === 'UserRejectedRequestError') {
console.log('User rejected chain switch')
}
}Switches to a different account within the connected wallet.
/**
* Switches to a different account
* @param config - Wagmi configuration
* @param parameters - Switch account parameters
* @returns Switch result with new account info
*/
function switchAccount<config extends Config>(
config: config,
parameters: SwitchAccountParameters<config>
): Promise<SwitchAccountReturnType<config>>;
interface SwitchAccountParameters<config extends Config> {
/** Target account address */
account: Address;
/** Specific connector to switch account for (optional) */
connector?: Connector;
}
interface SwitchAccountReturnType<config extends Config> {
/** New active account */
account: Address;
/** Chain ID */
chainId: config['chains'][number]['id'];
}
type SwitchAccountErrorType =
| BaseErrorType
| ConnectorAccountNotFoundErrorType
| ConnectorNotConnectedErrorType;Usage Example:
import { switchAccount, getConnections } from '@wagmi/core'
// Get available accounts
const connections = getConnections(config)
const availableAccounts = connections[0]?.accounts || []
if (availableAccounts.length > 1) {
try {
const result = await switchAccount(config, {
account: availableAccounts[1], // Switch to second account
})
console.log('Switched to account:', result.account)
} catch (error) {
console.error('Account switch failed:', error)
}
}Monitor connection state changes in real-time.
/**
* Watches for connection changes
* @param config - Wagmi configuration
* @param parameters - Watch parameters
* @returns Unsubscribe function
*/
function watchConnections<config extends Config>(
config: config,
parameters: WatchConnectionsParameters<config>
): WatchConnectionsReturnType;
interface WatchConnectionsParameters<config extends Config> {
/** Callback when connections change */
onChange(connections: GetConnectionsReturnType<config>): void;
}
type WatchConnectionsReturnType = () => void; // Unsubscribe function
/**
* Watches for connector changes
* @param config - Wagmi configuration
* @param parameters - Watch parameters
* @returns Unsubscribe function
*/
function watchConnectors<config extends Config>(
config: config,
parameters: WatchConnectorsParameters<config>
): WatchConnectorsReturnType;
interface WatchConnectorsParameters<config extends Config> {
/** Callback when connectors change */
onChange(connectors: GetConnectorsReturnType<config>): void;
}
type WatchConnectorsReturnType = () => void;Usage Example:
import { watchConnections, watchConnectors } from '@wagmi/core'
// Watch connection changes
const unsubscribeConnections = watchConnections(config, {
onChange(connections) {
console.log('Connection changed:', connections)
},
})
// Watch connector changes (useful for detecting new injected wallets)
const unsubscribeConnectors = watchConnectors(config, {
onChange(connectors) {
console.log('Available connectors:', connectors.map(c => c.name))
},
})
// Cleanup when component unmounts
// unsubscribeConnections()
// unsubscribeConnectors()Connection management functions can throw specific errors:
class ConnectorAlreadyConnectedError extends BaseError {
name: 'ConnectorAlreadyConnectedError';
}
class ConnectorNotConnectedError extends BaseError {
name: 'ConnectorNotConnectedError';
}
class ConnectorNotFoundError extends BaseError {
name: 'ConnectorNotFoundError';
}
class ConnectorAccountNotFoundError extends BaseError {
name: 'ConnectorAccountNotFoundError';
}
class SwitchChainNotSupportedError extends BaseError {
name: 'SwitchChainNotSupportedError';
}
class UserRejectedRequestError extends BaseError {
name: 'UserRejectedRequestError';
}Handle these errors appropriately to provide good user experience:
try {
await connect(config, { connector: injected() })
} catch (error) {
switch (error.name) {
case 'ConnectorAlreadyConnectedError':
console.log('Already connected to this wallet')
break
case 'UserRejectedRequestError':
console.log('User cancelled connection')
break
case 'ResourceUnavailableRpcError':
console.log('RPC connection failed')
break
default:
console.error('Connection failed:', error)
}
}Install with Tessl CLI
npx tessl i tessl/npm-wagmi--core