or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-chain-state.mdadvanced-features.mdblockchain-data-reading.mdconfiguration.mdconnection-management.mdcontract-interactions.mdens-operations.mdevent-watching.mdindex.mdsigning-verification.mdtanstack-query.mdtransaction-management.md

advanced-features.mddocs/

0

# Advanced Features

1

2

Advanced capabilities including EIP-5792 batch calls, wallet capabilities, code generation utilities, and experimental features.

3

4

## Capabilities

5

6

### Wallet Capabilities (EIP-5792)

7

8

Query wallet capabilities to understand what features are supported.

9

10

```typescript { .api }

11

/**

12

* Gets wallet capabilities (EIP-5792)

13

* @param config - Wagmi configuration

14

* @param parameters - Capabilities query parameters

15

* @returns Wallet capabilities

16

*/

17

function getCapabilities<config extends Config>(

18

config: config,

19

parameters?: GetCapabilitiesParameters<config>

20

): Promise<GetCapabilitiesReturnType>;

21

22

interface GetCapabilitiesParameters<config extends Config> {

23

/** Account to query capabilities for */

24

account?: Address;

25

/** Chain ID */

26

chainId?: config['chains'][number]['id'];

27

}

28

29

interface GetCapabilitiesReturnType {

30

[chainId: string]: {

31

/** Paymaster service support */

32

paymasterService?: {

33

supported: boolean;

34

};

35

/** Auxiliary funds support */

36

auxiliaryFunds?: {

37

supported: boolean;

38

};

39

/** Batch transaction support */

40

atomicBatch?: {

41

supported: boolean;

42

};

43

};

44

}

45

46

type GetCapabilitiesErrorType = BaseErrorType;

47

```

48

49

**Usage Example:**

50

51

```typescript

52

import { getCapabilities } from '@wagmi/core'

53

54

const capabilities = await getCapabilities(config)

55

console.log('Wallet capabilities:', capabilities)

56

57

// Check if current chain supports batch transactions

58

const chainId = getChainId(config)

59

const chainCapabilities = capabilities[chainId.toString()]

60

if (chainCapabilities?.atomicBatch?.supported) {

61

console.log('Batch transactions supported!')

62

}

63

```

64

65

### Batch Calls (EIP-5792)

66

67

Execute multiple operations in a single atomic transaction.

68

69

```typescript { .api }

70

/**

71

* Sends batch of calls (EIP-5792)

72

* @param config - Wagmi configuration

73

* @param parameters - Batch calls parameters

74

* @returns Batch call identifier

75

*/

76

function sendCalls<config extends Config>(

77

config: config,

78

parameters: SendCallsParameters<config>

79

): Promise<SendCallsReturnType>;

80

81

interface SendCallsParameters<config extends Config> {

82

/** Array of calls to execute */

83

calls: readonly {

84

/** Target contract address */

85

to?: Address;

86

/** Call data */

87

data?: Hex;

88

/** Value to send with call */

89

value?: bigint;

90

}[];

91

/** Chain ID to execute on */

92

chainId?: config['chains'][number]['id'];

93

/** Capabilities for the batch */

94

capabilities?: {

95

/** Paymaster service configuration */

96

paymasterService?: {

97

url: string;

98

};

99

/** Auxiliary funds configuration */

100

auxiliaryFunds?: {

101

supported: boolean;

102

};

103

};

104

}

105

106

type SendCallsReturnType = string; // Batch identifier

107

108

/**

109

* Gets status of batch calls

110

* @param config - Wagmi configuration

111

* @param parameters - Status query parameters

112

* @returns Batch status information

113

*/

114

function getCallsStatus<config extends Config>(

115

config: config,

116

parameters: GetCallsStatusParameters<config>

117

): Promise<GetCallsStatusReturnType>;

118

119

interface GetCallsStatusParameters<config extends Config> {

120

/** Batch identifier */

121

id: string;

122

/** Chain ID */

123

chainId?: config['chains'][number]['id'];

124

}

125

126

interface GetCallsStatusReturnType {

127

/** Batch status */

128

status: 'PENDING' | 'CONFIRMED';

129

/** Transaction receipts (if confirmed) */

130

receipts?: TransactionReceipt[];

131

}

132

133

/**

134

* Waits for batch calls to complete

135

* @param config - Wagmi configuration

136

* @param parameters - Wait parameters

137

* @returns Final batch status

138

*/

139

function waitForCallsStatus<config extends Config>(

140

config: config,

141

parameters: WaitForCallsStatusParameters<config>

142

): Promise<WaitForCallsStatusReturnType>;

143

144

interface WaitForCallsStatusParameters<config extends Config> {

145

/** Batch identifier */

146

id: string;

147

/** Chain ID */

148

chainId?: config['chains'][number]['id'];

149

/** Polling interval */

150

pollingInterval?: number;

151

/** Timeout */

152

timeout?: number;

153

}

154

155

type WaitForCallsStatusReturnType = GetCallsStatusReturnType;

156

```

157

158

**Usage Example:**

159

160

```typescript

161

import {

162

sendCalls,

163

waitForCallsStatus,

164

encodeFunctionData

165

} from '@wagmi/core'

166

167

// Batch multiple token approvals

168

const batchId = await sendCalls(config, {

169

calls: [

170

{

171

to: '0xTokenA',

172

data: encodeFunctionData({

173

abi: erc20Abi,

174

functionName: 'approve',

175

args: ['0xSpender', 1000000n],

176

}),

177

},

178

{

179

to: '0xTokenB',

180

data: encodeFunctionData({

181

abi: erc20Abi,

182

functionName: 'approve',

183

args: ['0xSpender', 2000000n],

184

}),

185

},

186

],

187

})

188

189

console.log('Batch sent:', batchId)

190

191

// Wait for completion

192

const result = await waitForCallsStatus(config, {

193

id: batchId,

194

})

195

196

if (result.status === 'CONFIRMED') {

197

console.log('All approvals confirmed!')

198

console.log('Receipts:', result.receipts?.length)

199

}

200

```

201

202

### Code Generation

203

204

Generate type-safe contract interaction functions.

205

206

```typescript { .api }

207

/**

208

* Creates typed read contract function

209

* @param parameters - Read contract creation parameters

210

* @returns Typed read function

211

*/

212

function createReadContract<TAbi extends Abi>(

213

parameters: CreateReadContractParameters<TAbi>

214

): CreateReadContractReturnType<TAbi>;

215

216

interface CreateReadContractParameters<TAbi extends Abi> {

217

/** Contract ABI */

218

abi: TAbi;

219

/** Contract address or address resolver */

220

address?: Address | Record<number, Address>;

221

}

222

223

type CreateReadContractReturnType<TAbi extends Abi> = <

224

TFunctionName extends string

225

>(

226

config: Config,

227

parameters: {

228

functionName: TFunctionName;

229

args?: unknown[];

230

chainId?: number;

231

}

232

) => Promise<any>;

233

234

/**

235

* Creates typed write contract function

236

* @param parameters - Write contract creation parameters

237

* @returns Typed write function

238

*/

239

function createWriteContract<TAbi extends Abi>(

240

parameters: CreateWriteContractParameters<TAbi>

241

): CreateWriteContractReturnType<TAbi>;

242

243

interface CreateWriteContractParameters<TAbi extends Abi> {

244

/** Contract ABI */

245

abi: TAbi;

246

/** Contract address or address resolver */

247

address?: Address | Record<number, Address>;

248

}

249

250

type CreateWriteContractReturnType<TAbi extends Abi> = <

251

TFunctionName extends string

252

>(

253

config: Config,

254

parameters: {

255

functionName: TFunctionName;

256

args?: unknown[];

257

chainId?: number;

258

}

259

) => Promise<Hash>;

260

261

/**

262

* Creates typed simulate contract function

263

* @param parameters - Simulate contract creation parameters

264

* @returns Typed simulate function

265

*/

266

function createSimulateContract<TAbi extends Abi>(

267

parameters: CreateSimulateContractParameters<TAbi>

268

): CreateSimulateContractReturnType<TAbi>;

269

270

interface CreateSimulateContractParameters<TAbi extends Abi> {

271

/** Contract ABI */

272

abi: TAbi;

273

/** Contract address or address resolver */

274

address?: Address | Record<number, Address>;

275

}

276

277

type CreateSimulateContractReturnType<TAbi extends Abi> = <

278

TFunctionName extends string

279

>(

280

config: Config,

281

parameters: {

282

functionName: TFunctionName;

283

args?: unknown[];

284

chainId?: number;

285

}

286

) => Promise<{ result: any; request: any }>;

287

288

/**

289

* Creates typed contract event watcher

290

* @param parameters - Event watcher creation parameters

291

* @returns Typed event watcher function

292

*/

293

function createWatchContractEvent<TAbi extends Abi>(

294

parameters: CreateWatchContractEventParameters<TAbi>

295

): CreateWatchContractEventReturnType<TAbi>;

296

297

interface CreateWatchContractEventParameters<TAbi extends Abi> {

298

/** Contract ABI */

299

abi: TAbi;

300

/** Contract address or address resolver */

301

address?: Address | Record<number, Address>;

302

}

303

304

type CreateWatchContractEventReturnType<TAbi extends Abi> = <

305

TEventName extends string

306

>(

307

config: Config,

308

parameters: {

309

eventName?: TEventName;

310

args?: Record<string, any>;

311

onLogs: (logs: Log[]) => void;

312

chainId?: number;

313

}

314

) => () => void;

315

```

316

317

**Usage Example:**

318

319

```typescript

320

import {

321

createReadContract,

322

createWriteContract,

323

createWatchContractEvent

324

} from '@wagmi/core/codegen'

325

326

// Create typed contract functions

327

const readToken = createReadContract({

328

abi: erc20Abi,

329

address: {

330

1: '0xMainnetTokenAddress',

331

137: '0xPolygonTokenAddress',

332

},

333

})

334

335

const writeToken = createWriteContract({

336

abi: erc20Abi,

337

address: {

338

1: '0xMainnetTokenAddress',

339

137: '0xPolygonTokenAddress',

340

},

341

})

342

343

const watchToken = createWatchContractEvent({

344

abi: erc20Abi,

345

address: {

346

1: '0xMainnetTokenAddress',

347

137: '0xPolygonTokenAddress',

348

},

349

})

350

351

// Use typed functions

352

const balance = await readToken(config, {

353

functionName: 'balanceOf',

354

args: ['0xUserAddress'],

355

chainId: 1,

356

})

357

358

const transferHash = await writeToken(config, {

359

functionName: 'transfer',

360

args: ['0xRecipient', 1000000n],

361

chainId: 1,

362

})

363

364

const unsubscribe = watchToken(config, {

365

eventName: 'Transfer',

366

args: { from: '0xUserAddress' },

367

onLogs: (logs) => {

368

console.log('Transfer events:', logs)

369

},

370

chainId: 1,

371

})

372

```

373

374

### Watch Asset

375

376

Add tokens to wallet's watch list.

377

378

```typescript { .api }

379

/**

380

* Adds token to wallet watch list

381

* @param config - Wagmi configuration

382

* @param parameters - Watch asset parameters

383

* @returns Success status

384

*/

385

function watchAsset<config extends Config>(

386

config: config,

387

parameters: WatchAssetParameters<config>

388

): Promise<WatchAssetReturnType>;

389

390

interface WatchAssetParameters<config extends Config> {

391

/** Asset type (always 'ERC20' for tokens) */

392

type: 'ERC20';

393

/** Token contract address */

394

address: Address;

395

/** Token symbol */

396

symbol: string;

397

/** Token decimals */

398

decimals: number;

399

/** Token icon URL */

400

image?: string;

401

/** Chain ID */

402

chainId?: config['chains'][number]['id'];

403

}

404

405

type WatchAssetReturnType = boolean;

406

407

type WatchAssetErrorType =

408

| BaseErrorType

409

| UserRejectedRequestErrorType;

410

```

411

412

**Usage Example:**

413

414

```typescript

415

import { watchAsset } from '@wagmi/core'

416

417

const added = await watchAsset(config, {

418

type: 'ERC20',

419

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

420

symbol: 'CUSTOM',

421

decimals: 18,

422

image: 'https://example.com/token-icon.png',

423

})

424

425

if (added) {

426

console.log('Token added to wallet!')

427

} else {

428

console.log('User declined to add token')

429

}

430

```

431

432

### Custom Connectors

433

434

Create custom wallet connectors for specialized connection methods.

435

436

```typescript { .api }

437

/**

438

* Creates a custom connector

439

* @param connectorFn - Connector implementation function

440

* @returns Custom connector function

441

*/

442

function createConnector<TProvider, TOptions = any>(

443

connectorFn: CreateConnectorFn<TProvider, TOptions>

444

): CreateConnectorFn<TProvider, TOptions>;

445

446

interface CreateConnectorFn<TProvider = any, TOptions = any> {

447

(options?: TOptions): (config: Config) => Connector<TProvider>;

448

}

449

450

interface Connector<TProvider = any> {

451

/** Unique connector ID */

452

id: string;

453

/** Display name */

454

name: string;

455

/** Connector type */

456

type: string;

457

/** Connector icon URL */

458

icon?: string;

459

/** Reverse Domain Name System identifier */

460

rdns?: string | readonly string[];

461

462

/** Setup function called once */

463

setup?(): Promise<void>;

464

465

/** Connect to wallet */

466

connect(parameters?: {

467

chainId?: number;

468

isReconnecting?: boolean;

469

}): Promise<{

470

accounts: readonly Address[];

471

chainId: number;

472

}>;

473

474

/** Disconnect from wallet */

475

disconnect(): Promise<void>;

476

477

/** Get connected accounts */

478

getAccounts(): Promise<readonly Address[]>;

479

480

/** Get current chain ID */

481

getChainId(): Promise<number>;

482

483

/** Get provider instance */

484

getProvider(): Promise<TProvider>;

485

486

/** Check if authorized */

487

isAuthorized(): Promise<boolean>;

488

489

/** Switch chain (optional) */

490

switchChain?(parameters: { chainId: number }): Promise<Chain>;

491

492

/** Event handlers */

493

onAccountsChanged?(accounts: string[]): void;

494

onChainChanged?(chainId: string | number): void;

495

onConnect?(connectInfo: { chainId: string | number }): void;

496

onDisconnect?(error?: { code: number; message: string }): void;

497

onMessage?(message: { type: string; data?: any }): void;

498

}

499

```

500

501

**Usage Example:**

502

503

```typescript

504

import { createConnector } from '@wagmi/core'

505

506

// Create a custom WebSocket-based connector

507

const webSocketConnector = createConnector((config) => ({

508

id: 'websocket-wallet',

509

name: 'WebSocket Wallet',

510

type: 'webSocket',

511

512

async setup() {

513

// Initialize WebSocket connection

514

this.ws = new WebSocket('wss://wallet.example.com')

515

},

516

517

async connect() {

518

if (!this.ws) await this.setup()

519

520

// Send connection request

521

this.ws.send(JSON.stringify({ type: 'connect' }))

522

523

// Wait for response

524

return new Promise((resolve, reject) => {

525

this.ws.onmessage = (event) => {

526

const data = JSON.parse(event.data)

527

if (data.type === 'connected') {

528

resolve({

529

accounts: data.accounts,

530

chainId: data.chainId,

531

})

532

} else if (data.type === 'error') {

533

reject(new Error(data.message))

534

}

535

}

536

})

537

},

538

539

async disconnect() {

540

if (this.ws) {

541

this.ws.send(JSON.stringify({ type: 'disconnect' }))

542

this.ws.close()

543

}

544

},

545

546

async getAccounts() {

547

// Implementation

548

return []

549

},

550

551

async getChainId() {

552

// Implementation

553

return 1

554

},

555

556

async getProvider() {

557

return this.ws

558

},

559

560

async isAuthorized() {

561

return this.ws?.readyState === WebSocket.OPEN

562

},

563

}))

564

565

// Use custom connector

566

const config = createConfig({

567

connectors: [webSocketConnector()],

568

// ... other config

569

})

570

```

571

572

### Advanced Transport Configuration

573

574

Configure advanced transport options.

575

576

```typescript { .api }

577

/**

578

* Fallback transport that tries multiple transports in order

579

* @param transports - Array of transports to try

580

* @param config - Fallback configuration

581

* @returns Fallback transport

582

*/

583

function fallback<TTransport extends Transport>(

584

transports: TTransport[],

585

config?: FallbackConfig

586

): FallbackTransport<TTransport>;

587

588

interface FallbackConfig {

589

/** Number of times to retry */

590

retryCount?: number;

591

/** Delay between retries in ms */

592

retryDelay?: number;

593

/** Rank transports by priority */

594

rank?: boolean;

595

}

596

597

/**

598

* Unstable connector transport (experimental)

599

* @param config - Connector transport configuration

600

* @returns Connector transport

601

*/

602

function unstable_connector(config: ConnectorTransportConfig): ConnectorTransport;

603

604

interface ConnectorTransportConfig {

605

/** Connector to use for transport */

606

connector: Connector;

607

}

608

```

609

610

**Usage Example:**

611

612

```typescript

613

import { fallback, http, webSocket, unstable_connector } from '@wagmi/core'

614

615

const config = createConfig({

616

chains: [mainnet, polygon],

617

transports: {

618

[mainnet.id]: fallback([

619

http('https://eth-mainnet.alchemyapi.io/v2/...'), // Primary

620

http('https://mainnet.infura.io/v3/...'), // Fallback 1

621

http(), // Public RPC fallback

622

], {

623

retryCount: 3,

624

retryDelay: 1000,

625

}),

626

[polygon.id]: webSocket('wss://polygon-rpc.com'),

627

},

628

})

629

630

// Using connector transport (experimental)

631

const configWithConnectorTransport = createConfig({

632

chains: [mainnet],

633

transports: {

634

[mainnet.id]: unstable_connector({

635

connector: injected(),

636

}),

637

},

638

})

639

```