VanillaJS library for Ethereum blockchain interactions with reactive primitives and utilities for building Ethereum applications
npx @tessl/cli install tessl/npm-wagmi--core@2.20.00
# @wagmi/core
1
2
@wagmi/core is a VanillaJS library for Ethereum blockchain interactions that provides reactive primitives and utilities for building Ethereum applications. It serves as the core foundation for the Wagmi ecosystem, offering comprehensive wallet connection management, contract interactions, transaction handling, and blockchain data fetching with full TypeScript support and framework-agnostic design.
3
4
## Package Information
5
6
- **Package Name**: @wagmi/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @wagmi/core viem`
10
11
## Core Imports
12
13
```typescript
14
import { createConfig, http } from '@wagmi/core'
15
import { mainnet, sepolia } from '@wagmi/core/chains'
16
```
17
18
Standard action imports:
19
20
```typescript
21
import { connect, disconnect, getAccount, getBalance } from '@wagmi/core'
22
```
23
24
Selective imports for tree-shaking:
25
26
```typescript
27
import { connect } from '@wagmi/core/actions'
28
import { getBalanceQueryOptions } from '@wagmi/core/query'
29
```
30
31
For CommonJS:
32
33
```javascript
34
const { createConfig, connect, getAccount } = require('@wagmi/core')
35
```
36
37
## Basic Usage
38
39
```typescript
40
import { createConfig, http, connect, getAccount, getBalance } from '@wagmi/core'
41
import { mainnet, sepolia } from '@wagmi/core/chains'
42
import { injected } from '@wagmi/core/connectors'
43
44
// 1. Create and configure wagmi
45
const config = createConfig({
46
chains: [mainnet, sepolia],
47
connectors: [injected()],
48
transports: {
49
[mainnet.id]: http(),
50
[sepolia.id]: http(),
51
},
52
})
53
54
// 2. Connect to wallet
55
await connect(config, { connector: injected() })
56
57
// 3. Get account information
58
const account = getAccount(config)
59
console.log('Connected account:', account.address)
60
61
// 4. Get account balance
62
const balance = await getBalance(config, {
63
address: account.address,
64
})
65
console.log('Balance:', balance.formatted, balance.symbol)
66
```
67
68
## Architecture
69
70
@wagmi/core is built around several key architectural patterns:
71
72
- **Config-first Design**: Central `Config` object manages chains, connectors, and transports
73
- **Action-based API**: Pure functions that take config as first parameter for all operations
74
- **Reactive State Management**: Built on Zustand with automatic state synchronization
75
- **Modular Exports**: Multiple entry points (`/actions`, `/query`, `/chains`) for optimal tree-shaking
76
- **Transport Abstraction**: Pluggable transport layer supporting HTTP, WebSocket, and custom transports
77
- **Connector System**: Extensible wallet connection system with built-in and custom connector support
78
- **Type Safety**: Full TypeScript integration with generic type preservation and inference
79
80
## Capabilities
81
82
### Configuration & Setup
83
84
Core configuration system for initializing wagmi with chains, connectors, and transports. Essential for all wagmi applications.
85
86
```typescript { .api }
87
function createConfig<
88
chains extends readonly [Chain, ...Chain[]],
89
transports extends Record<chains[number]['id'], Transport>
90
>(parameters: CreateConfigParameters<chains, transports>): Config<chains, transports>;
91
92
interface CreateConfigParameters<chains, transports> {
93
chains: chains;
94
connectors?: CreateConnectorFn[];
95
transports: transports;
96
storage?: Storage;
97
ssr?: boolean;
98
syncConnectedChain?: boolean;
99
multiInjectedProviderDiscovery?: boolean;
100
}
101
```
102
103
[Configuration & Setup](./configuration.md)
104
105
### Connection Management
106
107
Wallet connection, disconnection, and network switching functionality. Handles wallet lifecycle and chain management.
108
109
```typescript { .api }
110
function connect<config extends Config>(
111
config: config,
112
parameters: ConnectParameters<config>
113
): Promise<ConnectReturnType<config>>;
114
115
function disconnect(config: Config, parameters?: DisconnectParameters): Promise<DisconnectReturnType>;
116
117
function switchChain<config extends Config>(
118
config: config,
119
parameters: SwitchChainParameters<config>
120
): Promise<SwitchChainReturnType<config>>;
121
```
122
123
[Connection Management](./connection-management.md)
124
125
### Account & Chain State
126
127
Access to current account information, chain details, and connection status. Essential for understanding application state.
128
129
```typescript { .api }
130
function getAccount<config extends Config>(config: config): GetAccountReturnType<config>;
131
132
function getChainId<config extends Config>(config: config): GetChainIdReturnType<config>;
133
134
function getConnections<config extends Config>(config: config): GetConnectionsReturnType<config>;
135
136
interface GetAccountReturnType<config extends Config> {
137
address?: Address;
138
addresses?: readonly Address[];
139
chain?: Chain;
140
chainId?: number;
141
connector?: Connector;
142
isConnected: boolean;
143
isConnecting: boolean;
144
isDisconnected: boolean;
145
isReconnecting: boolean;
146
status: 'connected' | 'connecting' | 'disconnected' | 'reconnecting';
147
}
148
```
149
150
[Account & Chain State](./account-chain-state.md)
151
152
### Blockchain Data Reading
153
154
Comprehensive blockchain data fetching including balances, blocks, transactions, and contract state. Core read operations for dApps.
155
156
```typescript { .api }
157
function getBalance<config extends Config>(
158
config: config,
159
parameters: GetBalanceParameters<config>
160
): Promise<GetBalanceReturnType>;
161
162
function getBlock<config extends Config>(
163
config: config,
164
parameters?: GetBlockParameters<config>
165
): Promise<GetBlockReturnType>;
166
167
function getTransaction<config extends Config>(
168
config: config,
169
parameters: GetTransactionParameters<config>
170
): Promise<GetTransactionReturnType>;
171
172
interface GetBalanceReturnType {
173
decimals: number;
174
formatted: string;
175
symbol: string;
176
value: bigint;
177
}
178
```
179
180
[Blockchain Data Reading](./blockchain-data-reading.md)
181
182
### Contract Interactions
183
184
Smart contract reading, writing, simulation, and deployment. Complete contract interaction suite with type safety.
185
186
```typescript { .api }
187
function readContract<config extends Config>(
188
config: config,
189
parameters: ReadContractParameters<config>
190
): Promise<ReadContractReturnType>;
191
192
function writeContract<config extends Config>(
193
config: config,
194
parameters: WriteContractParameters<config>
195
): Promise<WriteContractReturnType>;
196
197
function simulateContract<config extends Config>(
198
config: config,
199
parameters: SimulateContractParameters<config>
200
): Promise<SimulateContractReturnType>;
201
202
function deployContract<config extends Config>(
203
config: config,
204
parameters: DeployContractParameters<config>
205
): Promise<DeployContractReturnType>;
206
```
207
208
[Contract Interactions](./contract-interactions.md)
209
210
### Transaction Management
211
212
Transaction sending, estimation, waiting, and monitoring. Complete transaction lifecycle management.
213
214
```typescript { .api }
215
function sendTransaction<config extends Config>(
216
config: config,
217
parameters: SendTransactionParameters<config>
218
): Promise<SendTransactionReturnType>;
219
220
function estimateGas<config extends Config>(
221
config: config,
222
parameters: EstimateGasParameters<config>
223
): Promise<EstimateGasReturnType>;
224
225
function waitForTransactionReceipt<config extends Config>(
226
config: config,
227
parameters: WaitForTransactionReceiptParameters<config>
228
): Promise<WaitForTransactionReceiptReturnType>;
229
230
function prepareTransactionRequest<config extends Config>(
231
config: config,
232
parameters: PrepareTransactionRequestParameters<config>
233
): Promise<PrepareTransactionRequestReturnType>;
234
```
235
236
[Transaction Management](./transaction-management.md)
237
238
### Signing & Verification
239
240
Message and typed data signing with EIP-712 support. Essential for authentication and authorization flows.
241
242
```typescript { .api }
243
function signMessage<config extends Config>(
244
config: config,
245
parameters: SignMessageParameters<config>
246
): Promise<SignMessageReturnType>;
247
248
function signTypedData<config extends Config>(
249
config: config,
250
parameters: SignTypedDataParameters<config>
251
): Promise<SignTypedDataReturnType>;
252
253
function verifyMessage<config extends Config>(
254
config: config,
255
parameters: VerifyMessageParameters<config>
256
): Promise<VerifyMessageReturnType>;
257
258
interface SignTypedDataParameters<config extends Config> {
259
types: Record<string, Array<{ name: string; type: string }>>;
260
primaryType: string;
261
domain?: TypedDataDomain;
262
message: Record<string, any>;
263
}
264
```
265
266
[Signing & Verification](./signing-verification.md)
267
268
### ENS Operations
269
270
Ethereum Name Service resolution, reverse resolution, and metadata retrieval. Complete ENS integration.
271
272
```typescript { .api }
273
function getEnsAddress<config extends Config>(
274
config: config,
275
parameters: GetEnsAddressParameters<config>
276
): Promise<GetEnsAddressReturnType>;
277
278
function getEnsName<config extends Config>(
279
config: config,
280
parameters: GetEnsNameParameters<config>
281
): Promise<GetEnsNameReturnType>;
282
283
function getEnsAvatar<config extends Config>(
284
config: config,
285
parameters: GetEnsAvatarParameters<config>
286
): Promise<GetEnsAvatarReturnType>;
287
288
function getEnsText<config extends Config>(
289
config: config,
290
parameters: GetEnsTextParameters<config>
291
): Promise<GetEnsTextReturnType>;
292
```
293
294
[ENS Operations](./ens-operations.md)
295
296
### Event Watching & Subscriptions
297
298
Real-time event watching for accounts, chains, blocks, and contract events. Reactive programming support.
299
300
```typescript { .api }
301
function watchAccount<config extends Config>(
302
config: config,
303
parameters: WatchAccountParameters<config>
304
): WatchAccountReturnType;
305
306
function watchChainId<config extends Config>(
307
config: config,
308
parameters: WatchChainIdParameters<config>
309
): WatchChainIdReturnType;
310
311
function watchContractEvent<config extends Config>(
312
config: config,
313
parameters: WatchContractEventParameters<config>
314
): WatchContractEventReturnType;
315
316
function watchBlockNumber<config extends Config>(
317
config: config,
318
parameters: WatchBlockNumberParameters<config>
319
): WatchBlockNumberReturnType;
320
321
type WatchAccountReturnType = () => void; // Unsubscribe function
322
```
323
324
[Event Watching & Subscriptions](./event-watching.md)
325
326
### TanStack Query Integration
327
328
First-class TanStack Query support with query options, mutation options, and caching strategies.
329
330
```typescript { .api }
331
function getBalanceQueryOptions<config extends Config>(
332
config: config,
333
options: GetBalanceOptions<config>
334
): QueryOptions<GetBalanceData, GetBalanceErrorType>;
335
336
function connectMutationOptions<config extends Config>(
337
config: config
338
): MutationOptions<ConnectData, ConnectErrorType, ConnectVariables>;
339
340
// Query key generation
341
function getBalanceQueryKey(parameters?: GetBalanceParameters): GetBalanceQueryKey;
342
343
// Utility functions
344
function hashFn(queryKey: QueryKey): string;
345
function structuralSharing<T>(oldData: T | undefined, newData: T): T;
346
```
347
348
[TanStack Query Integration](./tanstack-query.md)
349
350
### Advanced Features
351
352
Advanced capabilities including EIP-5792 batch calls, wallet capabilities, code generation utilities, and experimental features.
353
354
```typescript { .api }
355
function getCapabilities<config extends Config>(
356
config: config,
357
parameters?: GetCapabilitiesParameters<config>
358
): Promise<GetCapabilitiesReturnType>;
359
360
function sendCalls<config extends Config>(
361
config: config,
362
parameters: SendCallsParameters<config>
363
): Promise<SendCallsReturnType>;
364
365
function createReadContract<TAbi extends Abi>(
366
parameters: CreateReadContractParameters<TAbi>
367
): CreateReadContractReturnType<TAbi>;
368
369
function createConnector<TProvider>(
370
connectorFn: CreateConnectorFn<TProvider>
371
): CreateConnectorFn<TProvider>;
372
```
373
374
[Advanced Features](./advanced-features.md)
375
376
### Client Access
377
378
Access to Viem clients for advanced operations and direct blockchain interactions.
379
380
```typescript { .api }
381
function getConnectorClient<config extends Config>(
382
config: config,
383
parameters?: GetConnectorClientParameters<config>
384
): Promise<GetConnectorClientReturnType<config>>;
385
386
function getWalletClient<config extends Config>(
387
config: config,
388
parameters?: GetWalletClientParameters<config>
389
): Promise<GetWalletClientReturnType<config>>;
390
391
interface GetConnectorClientParameters<config extends Config> {
392
/** Chain ID */
393
chainId?: config['chains'][number]['id'];
394
/** Specific connector to use */
395
connector?: Connector;
396
/** Account to use (optional) */
397
account?: Address | Account | null;
398
}
399
400
interface GetWalletClientParameters<config extends Config> {
401
/** Chain ID */
402
chainId?: config['chains'][number]['id'];
403
/** Specific connector to use */
404
connector?: Connector;
405
/** Account to use (optional) */
406
account?: Address | Account | null;
407
}
408
```
409
410
## Error Handling
411
412
@wagmi/core provides structured error handling with specific error types:
413
414
```typescript { .api }
415
class BaseError extends Error {
416
name: string;
417
message: string;
418
cause?: unknown;
419
}
420
421
class ConnectorNotFoundError extends BaseError {}
422
class ChainNotConfiguredError extends BaseError {}
423
class ConnectorNotConnectedError extends BaseError {}
424
```
425
426
All async functions can throw typed errors that should be handled appropriately in your application.
427
428
## Core Types
429
430
```typescript { .api }
431
interface Config<
432
chains extends readonly Chain[] = readonly Chain[],
433
transports extends Record<chains[number]['id'], Transport> = Record<chains[number]['id'], Transport>
434
> {
435
chains: chains;
436
connectors: readonly Connector[];
437
transports: transports;
438
storage: Storage;
439
}
440
441
interface Chain {
442
id: number;
443
name: string;
444
nativeCurrency: {
445
name: string;
446
symbol: string;
447
decimals: number;
448
};
449
rpcUrls: {
450
default: { http: readonly string[] };
451
public?: { http: readonly string[] };
452
};
453
blockExplorers?: {
454
default: { name: string; url: string };
455
};
456
}
457
458
interface Connector {
459
id: string;
460
name: string;
461
type: string;
462
connect(parameters?: unknown): Promise<{
463
accounts: readonly Address[];
464
chainId: number;
465
}>;
466
disconnect(): Promise<void>;
467
getAccounts(): Promise<readonly Address[]>;
468
getChainId(): Promise<number>;
469
}
470
```
471
472
## Utilities
473
474
@wagmi/core provides several utility functions for common operations:
475
476
### Serialization & Deserialization
477
478
Safe JSON serialization/deserialization with support for BigInt and Map types, handling circular references.
479
480
```typescript { .api }
481
function serialize(
482
value: any,
483
replacer?: (key: string, value: any) => any,
484
indent?: number,
485
circularReplacer?: (key: string, value: any, referenceKey: string) => any
486
): string;
487
488
function deserialize<T>(
489
value: string,
490
reviver?: (key: string, value: any) => any
491
): T;
492
```
493
494
### Deep Equality
495
496
Fast deep equality comparison for objects and arrays.
497
498
```typescript { .api }
499
function deepEqual(a: any, b: any): boolean;
500
```
501
502
### Version
503
504
Package version string for debugging and compatibility checks.
505
506
```typescript { .api }
507
const version: string; // Current: "2.20.3"
508
```