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

contract-interactions.mddocs/

0

# Contract Interactions

1

2

Smart contract reading, writing, simulation, and deployment. Complete contract interaction suite with type safety.

3

4

## Capabilities

5

6

### Read Contract

7

8

Reads data from smart contracts using view/pure functions.

9

10

```typescript { .api }

11

/**

12

* Reads from a smart contract

13

* @param config - Wagmi configuration

14

* @param parameters - Contract read parameters

15

* @returns Contract function result

16

*/

17

function readContract<config extends Config>(

18

config: config,

19

parameters: ReadContractParameters<config>

20

): Promise<ReadContractReturnType>;

21

22

interface ReadContractParameters<config extends Config> {

23

/** Contract address */

24

address: Address;

25

/** Contract ABI */

26

abi: Abi;

27

/** Function name to call */

28

functionName: string;

29

/** Function arguments */

30

args?: readonly unknown[];

31

/** Account to call from (optional) */

32

account?: Address;

33

/** Block number to call at */

34

blockNumber?: bigint;

35

/** Block tag */

36

blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

37

/** Chain ID to call on */

38

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

39

}

40

41

type ReadContractReturnType = any; // Depends on contract function return type

42

43

type ReadContractErrorType = BaseErrorType | ContractFunctionExecutionErrorType;

44

```

45

46

**Usage Example:**

47

48

```typescript

49

import { readContract } from '@wagmi/core'

50

51

// ERC-20 token balance

52

const balance = await readContract(config, {

53

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

54

abi: [

55

{

56

name: 'balanceOf',

57

type: 'function',

58

stateMutability: 'view',

59

inputs: [{ name: 'owner', type: 'address' }],

60

outputs: [{ type: 'uint256' }],

61

},

62

],

63

functionName: 'balanceOf',

64

args: ['0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e'],

65

})

66

console.log('Token balance:', balance.toString())

67

68

// Read at specific block

69

const historicalBalance = await readContract(config, {

70

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

71

abi: erc20Abi,

72

functionName: 'balanceOf',

73

args: ['0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e'],

74

blockNumber: 18500000n,

75

})

76

```

77

78

### Read Multiple Contracts (Multicall)

79

80

Efficiently reads from multiple contracts in a single call.

81

82

```typescript { .api }

83

/**

84

* Reads from multiple smart contracts in a single call

85

* @param config - Wagmi configuration

86

* @param parameters - Multiple contract read parameters

87

* @returns Array of contract function results

88

*/

89

function readContracts<config extends Config>(

90

config: config,

91

parameters: ReadContractsParameters<config>

92

): Promise<ReadContractsReturnType>;

93

94

interface ReadContractsParameters<config extends Config> {

95

/** Array of contract calls */

96

contracts: readonly {

97

address: Address;

98

abi: Abi;

99

functionName: string;

100

args?: readonly unknown[];

101

}[];

102

/** Block number to call at */

103

blockNumber?: bigint;

104

/** Block tag */

105

blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

106

/** Chain ID to call on */

107

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

108

/** Whether to allow failures */

109

allowFailure?: boolean;

110

/** Multicall batch size */

111

batchSize?: number;

112

}

113

114

interface ReadContractsReturnType {

115

/** Result or error for each contract call */

116

result?: any;

117

status: 'success' | 'failure';

118

error?: BaseError;

119

}[]

120

121

type ReadContractsErrorType = BaseErrorType;

122

```

123

124

**Usage Example:**

125

126

```typescript

127

import { readContracts } from '@wagmi/core'

128

129

// Read multiple ERC-20 token data

130

const results = await readContracts(config, {

131

contracts: [

132

{

133

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

134

abi: erc20Abi,

135

functionName: 'name',

136

},

137

{

138

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

139

abi: erc20Abi,

140

functionName: 'symbol',

141

},

142

{

143

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

144

abi: erc20Abi,

145

functionName: 'decimals',

146

},

147

{

148

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

149

abi: erc20Abi,

150

functionName: 'totalSupply',

151

},

152

],

153

})

154

155

results.forEach((result, index) => {

156

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

157

console.log(`Call ${index}:`, result.result)

158

} else {

159

console.error(`Call ${index} failed:`, result.error)

160

}

161

})

162

```

163

164

### Write Contract

165

166

Executes state-changing contract functions.

167

168

```typescript { .api }

169

/**

170

* Writes to a smart contract

171

* @param config - Wagmi configuration

172

* @param parameters - Contract write parameters

173

* @returns Transaction hash

174

*/

175

function writeContract<config extends Config>(

176

config: config,

177

parameters: WriteContractParameters<config>

178

): Promise<WriteContractReturnType>;

179

180

interface WriteContractParameters<config extends Config> {

181

/** Contract address */

182

address: Address;

183

/** Contract ABI */

184

abi: Abi;

185

/** Function name to call */

186

functionName: string;

187

/** Function arguments */

188

args?: readonly unknown[];

189

/** Account to send from (optional, uses connected account) */

190

account?: Address;

191

/** Chain ID to send on */

192

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

193

/** Gas limit */

194

gas?: bigint;

195

/** Gas price (legacy) */

196

gasPrice?: bigint;

197

/** Max fee per gas (EIP-1559) */

198

maxFeePerGas?: bigint;

199

/** Max priority fee per gas (EIP-1559) */

200

maxPriorityFeePerGas?: bigint;

201

/** Nonce */

202

nonce?: number;

203

/** Value to send with transaction */

204

value?: bigint;

205

}

206

207

type WriteContractReturnType = Hash; // Transaction hash

208

209

type WriteContractErrorType =

210

| BaseErrorType

211

| ContractFunctionExecutionErrorType

212

| UserRejectedRequestErrorType;

213

```

214

215

**Usage Example:**

216

217

```typescript

218

import { writeContract } from '@wagmi/core'

219

220

// ERC-20 transfer

221

const hash = await writeContract(config, {

222

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

223

abi: [

224

{

225

name: 'transfer',

226

type: 'function',

227

stateMutability: 'nonpayable',

228

inputs: [

229

{ name: 'to', type: 'address' },

230

{ name: 'amount', type: 'uint256' },

231

],

232

outputs: [{ type: 'bool' }],

233

},

234

],

235

functionName: 'transfer',

236

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

237

})

238

console.log('Transaction hash:', hash)

239

240

// Contract call with value (payable function)

241

const payableHash = await writeContract(config, {

242

address: '0xContractAddress',

243

abi: contractAbi,

244

functionName: 'deposit',

245

value: parseEther('0.1'), // Send 0.1 ETH

246

})

247

```

248

249

### Simulate Contract

250

251

Simulates contract execution before sending transaction.

252

253

```typescript { .api }

254

/**

255

* Simulates contract write before execution

256

* @param config - Wagmi configuration

257

* @param parameters - Contract simulation parameters

258

* @returns Simulation result with request data

259

*/

260

function simulateContract<config extends Config>(

261

config: config,

262

parameters: SimulateContractParameters<config>

263

): Promise<SimulateContractReturnType>;

264

265

interface SimulateContractParameters<config extends Config> {

266

/** Contract address */

267

address: Address;

268

/** Contract ABI */

269

abi: Abi;

270

/** Function name to simulate */

271

functionName: string;

272

/** Function arguments */

273

args?: readonly unknown[];

274

/** Account to simulate from */

275

account?: Address;

276

/** Chain ID to simulate on */

277

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

278

/** Gas limit */

279

gas?: bigint;

280

/** Gas price */

281

gasPrice?: bigint;

282

/** Max fee per gas */

283

maxFeePerGas?: bigint;

284

/** Max priority fee per gas */

285

maxPriorityFeePerGas?: bigint;

286

/** Nonce */

287

nonce?: number;

288

/** Value to send */

289

value?: bigint;

290

/** Block number to simulate at */

291

blockNumber?: bigint;

292

/** Block tag */

293

blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

294

}

295

296

interface SimulateContractReturnType {

297

/** Simulation result */

298

result: any;

299

/** Prepared transaction request */

300

request: {

301

address: Address;

302

abi: Abi;

303

functionName: string;

304

args?: readonly unknown[];

305

account: Address;

306

chainId: number;

307

gas?: bigint;

308

gasPrice?: bigint;

309

maxFeePerGas?: bigint;

310

maxPriorityFeePerGas?: bigint;

311

nonce?: number;

312

value?: bigint;

313

};

314

}

315

316

type SimulateContractErrorType =

317

| BaseErrorType

318

| ContractFunctionExecutionErrorType;

319

```

320

321

**Usage Example:**

322

323

```typescript

324

import { simulateContract, writeContract } from '@wagmi/core'

325

326

try {

327

// First simulate the transaction

328

const { result, request } = await simulateContract(config, {

329

address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

330

abi: erc20Abi,

331

functionName: 'transfer',

332

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

333

})

334

335

console.log('Simulation result:', result) // true for successful transfer

336

console.log('Gas estimate:', request.gas?.toString())

337

338

// If simulation succeeds, execute the transaction

339

const hash = await writeContract(config, request)

340

console.log('Transaction sent:', hash)

341

} catch (error) {

342

console.error('Simulation failed:', error)

343

// Handle error (insufficient balance, etc.)

344

}

345

```

346

347

### Deploy Contract

348

349

Deploys a new smart contract.

350

351

```typescript { .api }

352

/**

353

* Deploys a smart contract

354

* @param config - Wagmi configuration

355

* @param parameters - Contract deployment parameters

356

* @returns Transaction hash

357

*/

358

function deployContract<config extends Config>(

359

config: config,

360

parameters: DeployContractParameters<config>

361

): Promise<DeployContractReturnType>;

362

363

interface DeployContractParameters<config extends Config> {

364

/** Contract ABI */

365

abi: Abi;

366

/** Contract bytecode */

367

bytecode: Hex;

368

/** Constructor arguments */

369

args?: readonly unknown[];

370

/** Account to deploy from */

371

account?: Address;

372

/** Chain ID to deploy on */

373

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

374

/** Gas limit */

375

gas?: bigint;

376

/** Gas price */

377

gasPrice?: bigint;

378

/** Max fee per gas */

379

maxFeePerGas?: bigint;

380

/** Max priority fee per gas */

381

maxPriorityFeePerGas?: bigint;

382

/** Nonce */

383

nonce?: number;

384

/** Value to send with deployment */

385

value?: bigint;

386

}

387

388

type DeployContractReturnType = Hash; // Transaction hash

389

390

type DeployContractErrorType =

391

| BaseErrorType

392

| ContractFunctionExecutionErrorType

393

| UserRejectedRequestErrorType;

394

```

395

396

**Usage Example:**

397

398

```typescript

399

import { deployContract, waitForTransactionReceipt } from '@wagmi/core'

400

401

// Deploy a simple contract

402

const hash = await deployContract(config, {

403

abi: contractAbi,

404

bytecode: '0x608060405234801561001057600080fd5b50...', // Contract bytecode

405

args: ['Initial Value', 100n], // Constructor arguments

406

})

407

408

console.log('Deployment transaction:', hash)

409

410

// Wait for deployment to complete

411

const receipt = await waitForTransactionReceipt(config, { hash })

412

console.log('Contract deployed at:', receipt.contractAddress)

413

```

414

415

### Execute Calls

416

417

Executes arbitrary contract calls.

418

419

```typescript { .api }

420

/**

421

* Executes a contract call

422

* @param config - Wagmi configuration

423

* @param parameters - Call parameters

424

* @returns Call result

425

*/

426

function call<config extends Config>(

427

config: config,

428

parameters: CallParameters<config>

429

): Promise<CallReturnType>;

430

431

interface CallParameters<config extends Config> {

432

/** Target account address */

433

account?: Address;

434

/** Contract address to call */

435

to?: Address;

436

/** Call data */

437

data?: Hex;

438

/** Gas limit */

439

gas?: bigint;

440

/** Gas price */

441

gasPrice?: bigint;

442

/** Max fee per gas */

443

maxFeePerGas?: bigint;

444

/** Max priority fee per gas */

445

maxPriorityFeePerGas?: bigint;

446

/** Value to send */

447

value?: bigint;

448

/** Block number to call at */

449

blockNumber?: bigint;

450

/** Block tag */

451

blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

452

/** Chain ID to call on */

453

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

454

}

455

456

interface CallReturnType {

457

/** Return data */

458

data?: Hex;

459

}

460

461

type CallErrorType = BaseErrorType | CallExecutionErrorType;

462

463

/**

464

* Executes multiple calls in a single transaction

465

* @param config - Wagmi configuration

466

* @param parameters - Multicall parameters

467

* @returns Array of call results

468

*/

469

function multicall<config extends Config>(

470

config: config,

471

parameters: MulticallParameters<config>

472

): Promise<MulticallReturnType>;

473

474

interface MulticallParameters<config extends Config> {

475

/** Array of contract calls */

476

contracts: readonly {

477

address: Address;

478

abi: Abi;

479

functionName: string;

480

args?: readonly unknown[];

481

}[];

482

/** Account to call from */

483

account?: Address;

484

/** Chain ID to call on */

485

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

486

/** Block number to call at */

487

blockNumber?: bigint;

488

/** Block tag */

489

blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

490

/** Whether to allow failures */

491

allowFailure?: boolean;

492

}

493

494

type MulticallReturnType = (any | null)[];

495

```

496

497

**Usage Example:**

498

499

```typescript

500

import { call, multicall } from '@wagmi/core'

501

502

// Raw contract call

503

const result = await call(config, {

504

to: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',

505

data: '0x70a08231000000000000000000000000742d35cc6601c2f3ac5e5c7a9d16e4e6be4e6e9e', // balanceOf encoded

506

})

507

console.log('Call result:', result.data)

508

509

// Multicall for batch operations

510

const results = await multicall(config, {

511

contracts: [

512

{

513

address: '0xTokenA',

514

abi: erc20Abi,

515

functionName: 'balanceOf',

516

args: ['0xUser'],

517

},

518

{

519

address: '0xTokenB',

520

abi: erc20Abi,

521

functionName: 'balanceOf',

522

args: ['0xUser'],

523

},

524

],

525

})

526

console.log('Token A balance:', results[0])

527

console.log('Token B balance:', results[1])

528

```

529

530

## Code Generation Utilities

531

532

Generate type-safe contract interaction functions.

533

534

```typescript { .api }

535

/**

536

* Creates typed read contract function

537

* @param parameters - Read contract creation parameters

538

* @returns Typed read function

539

*/

540

function createReadContract<TAbi extends Abi>(

541

parameters: CreateReadContractParameters<TAbi>

542

): CreateReadContractReturnType<TAbi>;

543

544

interface CreateReadContractParameters<TAbi extends Abi> {

545

/** Contract ABI */

546

abi: TAbi;

547

/** Contract address or resolver */

548

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

549

}

550

551

type CreateReadContractReturnType<TAbi extends Abi> = <

552

TFunctionName extends string

553

>(

554

config: Config,

555

parameters: {

556

functionName: TFunctionName;

557

args?: unknown[];

558

chainId?: number;

559

}

560

) => Promise<any>;

561

562

/**

563

* Creates typed write contract function

564

* @param parameters - Write contract creation parameters

565

* @returns Typed write function

566

*/

567

function createWriteContract<TAbi extends Abi>(

568

parameters: CreateWriteContractParameters<TAbi>

569

): CreateWriteContractReturnType<TAbi>;

570

571

interface CreateWriteContractParameters<TAbi extends Abi> {

572

/** Contract ABI */

573

abi: TAbi;

574

/** Contract address or resolver */

575

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

576

}

577

578

type CreateWriteContractReturnType<TAbi extends Abi> = <

579

TFunctionName extends string

580

>(

581

config: Config,

582

parameters: {

583

functionName: TFunctionName;

584

args?: unknown[];

585

chainId?: number;

586

}

587

) => Promise<Hash>;

588

589

/**

590

* Creates typed simulate contract function

591

* @param parameters - Simulate contract creation parameters

592

* @returns Typed simulate function

593

*/

594

function createSimulateContract<TAbi extends Abi>(

595

parameters: CreateSimulateContractParameters<TAbi>

596

): CreateSimulateContractReturnType<TAbi>;

597

598

interface CreateSimulateContractParameters<TAbi extends Abi> {

599

/** Contract ABI */

600

abi: TAbi;

601

/** Contract address or resolver */

602

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

603

}

604

605

type CreateSimulateContractReturnType<TAbi extends Abi> = <

606

TFunctionName extends string

607

>(

608

config: Config,

609

parameters: {

610

functionName: TFunctionName;

611

args?: unknown[];

612

chainId?: number;

613

}

614

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

615

```

616

617

**Usage Example:**

618

619

```typescript

620

import { createReadContract, createWriteContract } from '@wagmi/core/codegen'

621

622

// Create typed contract functions

623

const readERC20 = createReadContract({

624

abi: erc20Abi,

625

address: {

626

1: '0xMainnetAddress',

627

137: '0xPolygonAddress',

628

},

629

})

630

631

const writeERC20 = createWriteContract({

632

abi: erc20Abi,

633

address: {

634

1: '0xMainnetAddress',

635

137: '0xPolygonAddress',

636

},

637

})

638

639

// Use typed functions

640

const balance = await readERC20(config, {

641

functionName: 'balanceOf',

642

args: ['0xUser'],

643

chainId: 1,

644

})

645

646

const transferHash = await writeERC20(config, {

647

functionName: 'transfer',

648

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

649

chainId: 1,

650

})

651

```