0
# Blockchain Data Reading
1
2
Comprehensive blockchain data fetching including balances, blocks, transactions, and contract state. Core read operations for dApps.
3
4
## Capabilities
5
6
### Get Balance
7
8
Retrieves native token or ERC-20 token balance for an account.
9
10
```typescript { .api }
11
/**
12
* Gets account balance for native token or ERC-20 tokens
13
* @param config - Wagmi configuration
14
* @param parameters - Balance query parameters
15
* @returns Balance information with formatted value
16
*/
17
function getBalance<config extends Config>(
18
config: config,
19
parameters: GetBalanceParameters<config>
20
): Promise<GetBalanceReturnType>;
21
22
interface GetBalanceParameters<config extends Config> {
23
/** Account address to check balance for */
24
address: Address;
25
/** ERC-20 token contract address (optional, defaults to native token) */
26
token?: Address;
27
/** Block number or tag to query at */
28
blockNumber?: bigint;
29
/** Block tag ('latest', 'earliest', 'pending', 'safe', 'finalized') */
30
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
31
/** Chain ID to query on */
32
chainId?: config['chains'][number]['id'];
33
/** Unit for formatting (deprecated) */
34
unit?: Unit;
35
}
36
37
interface GetBalanceReturnType {
38
/** Token decimals */
39
decimals: number;
40
/** Formatted balance string */
41
formatted: string;
42
/** Token symbol */
43
symbol: string;
44
/** Raw balance value */
45
value: bigint;
46
}
47
48
type GetBalanceErrorType = BaseErrorType | viem_GetBalanceErrorType;
49
50
/** @deprecated Use getBalance instead */
51
const fetchBalance = getBalance;
52
```
53
54
**Usage Example:**
55
56
```typescript
57
import { getBalance } from '@wagmi/core'
58
59
// Get native ETH balance
60
const ethBalance = await getBalance(config, {
61
address: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
62
})
63
console.log(`ETH Balance: ${ethBalance.formatted} ${ethBalance.symbol}`)
64
65
// Get ERC-20 token balance (USDC)
66
const usdcBalance = await getBalance(config, {
67
address: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
68
token: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f', // USDC contract
69
})
70
console.log(`USDC Balance: ${usdcBalance.formatted} ${usdcBalance.symbol}`)
71
72
// Query at specific block
73
const historicalBalance = await getBalance(config, {
74
address: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
75
blockNumber: 18500000n,
76
})
77
```
78
79
### Get Block Information
80
81
Retrieves block information by number, hash, or tag.
82
83
```typescript { .api }
84
/**
85
* Gets block information
86
* @param config - Wagmi configuration
87
* @param parameters - Block query parameters (optional)
88
* @returns Block information
89
*/
90
function getBlock<config extends Config>(
91
config: config,
92
parameters?: GetBlockParameters<config>
93
): Promise<GetBlockReturnType>;
94
95
interface GetBlockParameters<config extends Config> {
96
/** Block number to retrieve */
97
blockNumber?: bigint;
98
/** Block hash to retrieve */
99
blockHash?: Hash;
100
/** Block tag */
101
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
102
/** Include transaction details */
103
includeTransactions?: boolean;
104
/** Chain ID to query */
105
chainId?: config['chains'][number]['id'];
106
}
107
108
interface GetBlockReturnType {
109
/** Block hash */
110
hash: Hash;
111
/** Block number */
112
number: bigint;
113
/** Parent block hash */
114
parentHash: Hash;
115
/** Timestamp */
116
timestamp: bigint;
117
/** Gas limit */
118
gasLimit: bigint;
119
/** Gas used */
120
gasUsed: bigint;
121
/** Miner/validator address */
122
miner: Address;
123
/** Transactions (hashes or full transactions) */
124
transactions: Hash[] | Transaction[];
125
/** Base fee per gas (EIP-1559) */
126
baseFeePerGas?: bigint;
127
/** Extra data */
128
extraData: Hex;
129
}
130
131
type GetBlockErrorType = BaseErrorType | viem_GetBlockErrorType;
132
```
133
134
**Usage Example:**
135
136
```typescript
137
import { getBlock } from '@wagmi/core'
138
139
// Get latest block
140
const latestBlock = await getBlock(config)
141
console.log('Latest block number:', latestBlock.number)
142
console.log('Block timestamp:', new Date(Number(latestBlock.timestamp) * 1000))
143
144
// Get specific block with transaction details
145
const blockWithTxs = await getBlock(config, {
146
blockNumber: 18500000n,
147
includeTransactions: true,
148
})
149
console.log('Transaction count:', blockWithTxs.transactions.length)
150
151
// Get block by hash
152
const blockByHash = await getBlock(config, {
153
blockHash: '0x1234567890abcdef...',
154
})
155
```
156
157
### Get Block Number
158
159
Retrieves the latest block number.
160
161
```typescript { .api }
162
/**
163
* Gets current block number
164
* @param config - Wagmi configuration
165
* @param parameters - Block number query parameters (optional)
166
* @returns Current block number
167
*/
168
function getBlockNumber<config extends Config>(
169
config: config,
170
parameters?: GetBlockNumberParameters<config>
171
): Promise<GetBlockNumberReturnType>;
172
173
interface GetBlockNumberParameters<config extends Config> {
174
/** Chain ID to query */
175
chainId?: config['chains'][number]['id'];
176
/** Cache time in milliseconds */
177
cacheTime?: number;
178
}
179
180
type GetBlockNumberReturnType = bigint;
181
182
type GetBlockNumberErrorType = BaseErrorType | viem_GetBlockNumberErrorType;
183
184
/** @deprecated Use getBlockNumber instead */
185
const fetchBlockNumber = getBlockNumber;
186
```
187
188
### Get Transaction Information
189
190
Retrieves transaction details by hash.
191
192
```typescript { .api }
193
/**
194
* Gets transaction details by hash
195
* @param config - Wagmi configuration
196
* @param parameters - Transaction query parameters
197
* @returns Transaction information
198
*/
199
function getTransaction<config extends Config>(
200
config: config,
201
parameters: GetTransactionParameters<config>
202
): Promise<GetTransactionReturnType>;
203
204
interface GetTransactionParameters<config extends Config> {
205
/** Transaction hash */
206
hash: Hash;
207
/** Chain ID to query */
208
chainId?: config['chains'][number]['id'];
209
}
210
211
interface GetTransactionReturnType {
212
/** Transaction hash */
213
hash: Hash;
214
/** Block hash */
215
blockHash?: Hash;
216
/** Block number */
217
blockNumber?: bigint;
218
/** Transaction index in block */
219
transactionIndex?: number;
220
/** From address */
221
from: Address;
222
/** To address */
223
to?: Address;
224
/** Value sent */
225
value: bigint;
226
/** Gas limit */
227
gas: bigint;
228
/** Gas price */
229
gasPrice?: bigint;
230
/** Max fee per gas (EIP-1559) */
231
maxFeePerGas?: bigint;
232
/** Max priority fee per gas (EIP-1559) */
233
maxPriorityFeePerGas?: bigint;
234
/** Transaction data */
235
input: Hex;
236
/** Nonce */
237
nonce: number;
238
/** Transaction type */
239
type: 'legacy' | 'eip2930' | 'eip1559';
240
}
241
242
type GetTransactionErrorType = BaseErrorType | viem_GetTransactionErrorType;
243
244
/** @deprecated Use getTransaction instead */
245
const fetchTransaction = getTransaction;
246
```
247
248
### Get Transaction Receipt
249
250
Retrieves transaction receipt with execution results.
251
252
```typescript { .api }
253
/**
254
* Gets transaction receipt
255
* @param config - Wagmi configuration
256
* @param parameters - Receipt query parameters
257
* @returns Transaction receipt
258
*/
259
function getTransactionReceipt<config extends Config>(
260
config: config,
261
parameters: GetTransactionReceiptParameters<config>
262
): Promise<GetTransactionReceiptReturnType>;
263
264
interface GetTransactionReceiptParameters<config extends Config> {
265
/** Transaction hash */
266
hash: Hash;
267
/** Chain ID to query */
268
chainId?: config['chains'][number]['id'];
269
}
270
271
interface GetTransactionReceiptReturnType {
272
/** Transaction hash */
273
transactionHash: Hash;
274
/** Block hash */
275
blockHash: Hash;
276
/** Block number */
277
blockNumber: bigint;
278
/** Transaction index */
279
transactionIndex: number;
280
/** From address */
281
from: Address;
282
/** To address */
283
to?: Address;
284
/** Gas used */
285
gasUsed: bigint;
286
/** Effective gas price */
287
effectiveGasPrice: bigint;
288
/** Status (1 = success, 0 = failure) */
289
status: 'success' | 'reverted';
290
/** Event logs */
291
logs: Log[];
292
/** Contract address (if deployment) */
293
contractAddress?: Address;
294
/** Cumulative gas used */
295
cumulativeGasUsed: bigint;
296
}
297
298
type GetTransactionReceiptErrorType = BaseErrorType | viem_GetTransactionReceiptErrorType;
299
```
300
301
**Usage Example:**
302
303
```typescript
304
import { getTransaction, getTransactionReceipt } from '@wagmi/core'
305
306
// Get transaction details
307
const tx = await getTransaction(config, {
308
hash: '0x1234567890abcdef...',
309
})
310
console.log('Transaction from:', tx.from)
311
console.log('Transaction to:', tx.to)
312
console.log('Value:', tx.value.toString())
313
314
// Get transaction receipt
315
const receipt = await getTransactionReceipt(config, {
316
hash: '0x1234567890abcdef...',
317
})
318
console.log('Transaction status:', receipt.status)
319
console.log('Gas used:', receipt.gasUsed.toString())
320
console.log('Logs:', receipt.logs.length)
321
```
322
323
### Get Gas Price and Fee Information
324
325
Retrieves current gas pricing information.
326
327
```typescript { .api }
328
/**
329
* Gets current gas price
330
* @param config - Wagmi configuration
331
* @param parameters - Gas price query parameters (optional)
332
* @returns Current gas price
333
*/
334
function getGasPrice<config extends Config>(
335
config: config,
336
parameters?: GetGasPriceParameters<config>
337
): Promise<GetGasPriceReturnType>;
338
339
interface GetGasPriceParameters<config extends Config> {
340
/** Chain ID to query */
341
chainId?: config['chains'][number]['id'];
342
}
343
344
type GetGasPriceReturnType = bigint;
345
346
/**
347
* Gets EIP-1559 fee estimates
348
* @param config - Wagmi configuration
349
* @param parameters - Fee estimation parameters (optional)
350
* @returns Fee per gas estimates
351
*/
352
function estimateFeesPerGas<config extends Config>(
353
config: config,
354
parameters?: EstimateFeesPerGasParameters<config>
355
): Promise<EstimateFeesPerGasReturnType>;
356
357
interface EstimateFeesPerGasParameters<config extends Config> {
358
/** Chain ID to query */
359
chainId?: config['chains'][number]['id'];
360
/** Fee multiplier */
361
formatUnits?: number;
362
}
363
364
interface EstimateFeesPerGasReturnType {
365
/** Max fee per gas */
366
maxFeePerGas: bigint;
367
/** Max priority fee per gas */
368
maxPriorityFeePerGas: bigint;
369
}
370
371
/**
372
* Gets max priority fee per gas estimate
373
* @param config - Wagmi configuration
374
* @param parameters - Priority fee parameters (optional)
375
* @returns Max priority fee per gas
376
*/
377
function estimateMaxPriorityFeePerGas<config extends Config>(
378
config: config,
379
parameters?: EstimateMaxPriorityFeePerGasParameters<config>
380
): Promise<EstimateMaxPriorityFeePerGasReturnType>;
381
382
interface EstimateMaxPriorityFeePerGasParameters<config extends Config> {
383
/** Chain ID to query */
384
chainId?: config['chains'][number]['id'];
385
}
386
387
type EstimateMaxPriorityFeePerGasReturnType = bigint;
388
```
389
390
**Usage Example:**
391
392
```typescript
393
import { getGasPrice, estimateFeesPerGas, estimateMaxPriorityFeePerGas } from '@wagmi/core'
394
395
// Get current gas price (legacy)
396
const gasPrice = await getGasPrice(config)
397
console.log('Gas price:', gasPrice.toString(), 'wei')
398
399
// Get EIP-1559 fees
400
const fees = await estimateFeesPerGas(config)
401
console.log('Max fee per gas:', fees.maxFeePerGas.toString())
402
console.log('Max priority fee:', fees.maxPriorityFeePerGas.toString())
403
404
// Get just priority fee
405
const priorityFee = await estimateMaxPriorityFeePerGas(config)
406
console.log('Priority fee:', priorityFee.toString())
407
```
408
409
### Get Fee History
410
411
Retrieves historical fee data for gas estimation.
412
413
```typescript { .api }
414
/**
415
* Gets fee history for gas estimation
416
* @param config - Wagmi configuration
417
* @param parameters - Fee history parameters
418
* @returns Historical fee data
419
*/
420
function getFeeHistory<config extends Config>(
421
config: config,
422
parameters: GetFeeHistoryParameters<config>
423
): Promise<GetFeeHistoryReturnType>;
424
425
interface GetFeeHistoryParameters<config extends Config> {
426
/** Number of blocks to include */
427
blockCount: number;
428
/** Reward percentiles to calculate */
429
rewardPercentiles: number[];
430
/** Chain ID to query */
431
chainId?: config['chains'][number]['id'];
432
}
433
434
interface GetFeeHistoryReturnType {
435
/** Base fee per gas for each block */
436
baseFeePerGas: bigint[];
437
/** Gas used ratio for each block */
438
gasUsedRatio: number[];
439
/** Reward percentiles for each block */
440
reward?: bigint[][];
441
}
442
443
type GetFeeHistoryErrorType = BaseErrorType | viem_GetFeeHistoryErrorType;
444
```
445
446
### Get Storage and Bytecode
447
448
Access contract storage and bytecode.
449
450
```typescript { .api }
451
/**
452
* Gets storage value at specific slot
453
* @param config - Wagmi configuration
454
* @param parameters - Storage query parameters
455
* @returns Storage value
456
*/
457
function getStorageAt<config extends Config>(
458
config: config,
459
parameters: GetStorageAtParameters<config>
460
): Promise<GetStorageAtReturnType>;
461
462
interface GetStorageAtParameters<config extends Config> {
463
/** Contract address */
464
address: Address;
465
/** Storage slot */
466
slot: Hex;
467
/** Block number to query at */
468
blockNumber?: bigint;
469
/** Block tag */
470
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
471
/** Chain ID to query */
472
chainId?: config['chains'][number]['id'];
473
}
474
475
type GetStorageAtReturnType = Hex;
476
477
/**
478
* Gets contract bytecode
479
* @param config - Wagmi configuration
480
* @param parameters - Bytecode query parameters
481
* @returns Contract bytecode
482
*/
483
function getBytecode<config extends Config>(
484
config: config,
485
parameters: GetBytecodeParameters<config>
486
): Promise<GetBytecodeReturnType>;
487
488
interface GetBytecodeParameters<config extends Config> {
489
/** Contract address */
490
address: Address;
491
/** Block number to query at */
492
blockNumber?: bigint;
493
/** Block tag */
494
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
495
/** Chain ID to query */
496
chainId?: config['chains'][number]['id'];
497
}
498
499
type GetBytecodeReturnType = Hex | undefined;
500
501
type GetStorageAtErrorType = BaseErrorType | viem_GetStorageAtErrorType;
502
type GetBytecodeErrorType = BaseErrorType | viem_GetBytecodeErrorType;
503
```
504
505
### Get ERC-20 Token Information
506
507
Retrieves ERC-20 token metadata.
508
509
```typescript { .api }
510
/**
511
* Gets ERC-20 token information
512
* @param config - Wagmi configuration
513
* @param parameters - Token query parameters
514
* @returns Token information
515
*/
516
function getToken<config extends Config>(
517
config: config,
518
parameters: GetTokenParameters<config>
519
): Promise<GetTokenReturnType>;
520
521
interface GetTokenParameters<config extends Config> {
522
/** Token contract address */
523
address: Address;
524
/** Chain ID to query */
525
chainId?: config['chains'][number]['id'];
526
/** Format units for decimals */
527
formatUnits?: 'ether' | 'gwei' | 'wei' | number;
528
}
529
530
interface GetTokenReturnType {
531
/** Token contract address */
532
address: Address;
533
/** Token decimals */
534
decimals: number;
535
/** Token name */
536
name: string;
537
/** Token symbol */
538
symbol: string;
539
/** Total supply */
540
totalSupply: {
541
formatted: string;
542
value: bigint;
543
};
544
}
545
546
type GetTokenErrorType = BaseErrorType | viem_GetTokenErrorType;
547
548
/** @deprecated Use getToken instead */
549
const fetchToken = getToken;
550
```
551
552
**Usage Example:**
553
554
```typescript
555
import { getToken } from '@wagmi/core'
556
557
// Get USDC token information
558
const usdc = await getToken(config, {
559
address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
560
})
561
562
console.log('Token info:', {
563
name: usdc.name,
564
symbol: usdc.symbol,
565
decimals: usdc.decimals,
566
totalSupply: usdc.totalSupply.formatted,
567
})
568
```
569
570
### Advanced Query Functions
571
572
Additional blockchain data queries.
573
574
```typescript { .api }
575
/**
576
* Gets transaction count (nonce) for account
577
* @param config - Wagmi configuration
578
* @param parameters - Transaction count parameters
579
* @returns Transaction count
580
*/
581
function getTransactionCount<config extends Config>(
582
config: config,
583
parameters: GetTransactionCountParameters<config>
584
): Promise<GetTransactionCountReturnType>;
585
586
interface GetTransactionCountParameters<config extends Config> {
587
/** Account address */
588
address: Address;
589
/** Block number or tag */
590
blockNumber?: bigint;
591
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
592
/** Chain ID to query */
593
chainId?: config['chains'][number]['id'];
594
}
595
596
type GetTransactionCountReturnType = number;
597
598
/**
599
* Gets transaction confirmations
600
* @param config - Wagmi configuration
601
* @param parameters - Confirmation query parameters
602
* @returns Number of confirmations
603
*/
604
function getTransactionConfirmations<config extends Config>(
605
config: config,
606
parameters: GetTransactionConfirmationsParameters<config>
607
): Promise<GetTransactionConfirmationsReturnType>;
608
609
interface GetTransactionConfirmationsParameters<config extends Config> {
610
/** Transaction hash */
611
hash: Hash;
612
/** Chain ID to query */
613
chainId?: config['chains'][number]['id'];
614
}
615
616
type GetTransactionConfirmationsReturnType = bigint;
617
618
/**
619
* Gets block transaction count
620
* @param config - Wagmi configuration
621
* @param parameters - Block transaction count parameters
622
* @returns Transaction count in block
623
*/
624
function getBlockTransactionCount<config extends Config>(
625
config: config,
626
parameters?: GetBlockTransactionCountParameters<config>
627
): Promise<GetBlockTransactionCountReturnType>;
628
629
interface GetBlockTransactionCountParameters<config extends Config> {
630
/** Block number */
631
blockNumber?: bigint;
632
/** Block hash */
633
blockHash?: Hash;
634
/** Block tag */
635
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
636
/** Chain ID to query */
637
chainId?: config['chains'][number]['id'];
638
}
639
640
type GetBlockTransactionCountReturnType = number;
641
```
642
643
**Usage Example:**
644
645
```typescript
646
import {
647
getTransactionCount,
648
getTransactionConfirmations,
649
getBlockTransactionCount
650
} from '@wagmi/core'
651
652
// Get account nonce
653
const nonce = await getTransactionCount(config, {
654
address: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
655
})
656
console.log('Account nonce:', nonce)
657
658
// Get transaction confirmations
659
const confirmations = await getTransactionConfirmations(config, {
660
hash: '0x1234567890abcdef...',
661
})
662
console.log('Confirmations:', confirmations.toString())
663
664
// Get transaction count in latest block
665
const txCount = await getBlockTransactionCount(config)
666
console.log('Transactions in latest block:', txCount)
667
```