or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-management.mdcore-web3.mdens.mdethereum-interaction.mdindex.mdproviders.mdsmart-contracts.mdutilities.md

smart-contracts.mddocs/

0

# Smart Contract Interaction

1

2

The Contract module provides comprehensive functionality for deploying, interacting with, and monitoring Ethereum smart contracts. It offers full TypeScript support with automatic type generation from ABI specifications and handles all aspects of contract lifecycle management.

3

4

## Capabilities

5

6

### Contract Constructor

7

8

Create contract instances for interaction with deployed contracts or deployment of new contracts.

9

10

```typescript { .api }

11

/**

12

* Creates a new contract instance

13

* @param jsonInterface - Contract ABI

14

* @param address - Contract address (optional for deployment)

15

* @param options - Contract options including gas, gasPrice, etc.

16

*/

17

class Contract<Abi extends ContractAbi> {

18

constructor(jsonInterface: Abi);

19

constructor(jsonInterface: Abi, address: Address);

20

constructor(jsonInterface: Abi, options: ContractInitOptions);

21

constructor(jsonInterface: Abi, address: Address, options: ContractInitOptions);

22

}

23

```

24

25

**Usage Examples:**

26

27

```typescript

28

// Create contract instance for existing contract

29

const abi = [...]; // Contract ABI

30

const contractAddress = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984';

31

const contract = new web3.eth.Contract(abi, contractAddress);

32

33

// Create contract instance for deployment

34

const contract = new web3.eth.Contract(abi);

35

36

// Create with options

37

const contract = new web3.eth.Contract(abi, contractAddress, {

38

from: '0x742C1382...',

39

gasPrice: '20000000000'

40

});

41

```

42

43

### Contract Methods

44

45

Execute contract functions with automatic encoding/decoding and full type safety.

46

47

```typescript { .api }

48

interface ContractMethods<Abi extends ContractAbi> {

49

[key: string]: ContractMethod<any, any>;

50

}

51

52

interface ContractMethod<Inputs, Outputs> {

53

/**

54

* Execute a call (read-only) to the contract method

55

* @param options - Call options

56

* @param blockNumber - Block number for the call

57

* @returns Method result

58

*/

59

call(options?: PayableCallOptions, blockNumber?: BlockNumberOrTag): Promise<Outputs>;

60

61

/**

62

* Send a transaction to execute the contract method

63

* @param options - Transaction options

64

* @returns PromiEvent with transaction receipt

65

*/

66

send(options: PayableTxOptions): PromiEvent<TransactionReceipt>;

67

68

/**

69

* Estimate gas required for the method execution

70

* @param options - Transaction options

71

* @returns Estimated gas amount

72

*/

73

estimateGas(options?: PayableCallOptions): Promise<bigint>;

74

75

/**

76

* Encode ABI for this method call

77

* @param options - Call options

78

* @returns Encoded ABI string

79

*/

80

encodeABI(options?: PayableCallOptions): string;

81

}

82

```

83

84

**Usage Examples:**

85

86

```typescript

87

// Call a read-only method

88

const totalSupply = await contract.methods.totalSupply().call();

89

const balance = await contract.methods.balanceOf('0x742C1382...').call();

90

91

// Send a transaction

92

const receipt = await contract.methods.transfer(

93

'0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',

94

web3.utils.toWei('10', 'ether')

95

).send({

96

from: '0x742C1382...',

97

gas: 100000

98

});

99

100

// Estimate gas

101

const gasEstimate = await contract.methods.transfer(

102

'0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',

103

web3.utils.toWei('10', 'ether')

104

).estimateGas({ from: '0x742C1382...' });

105

106

// Get encoded ABI

107

const encodedABI = contract.methods.transfer(

108

'0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',

109

web3.utils.toWei('10', 'ether')

110

).encodeABI();

111

```

112

113

### Contract Deployment

114

115

Deploy new contracts to the blockchain with constructor parameters and initialization options.

116

117

```typescript { .api }

118

interface ContractDeploySend<Abi extends ContractAbi> {

119

/**

120

* Send deployment transaction

121

* @param options - Deployment options

122

* @returns PromiEvent with contract instance

123

*/

124

send(options: PayableTxOptions): PromiEvent<Contract<Abi>>;

125

126

/**

127

* Estimate gas for deployment

128

* @param options - Deployment options

129

* @returns Estimated gas amount

130

*/

131

estimateGas(options?: PayableCallOptions): Promise<bigint>;

132

133

/**

134

* Encode deployment data

135

* @returns Encoded deployment data

136

*/

137

encodeABI(): string;

138

}

139

140

/**

141

* Deploy a new contract

142

* @param options - Deployment options including bytecode and constructor arguments

143

* @returns ContractDeploySend instance

144

*/

145

deploy(options: ContractDeployOptions): ContractDeploySend<Abi>;

146

```

147

148

**Usage Examples:**

149

150

```typescript

151

// Deploy a new contract

152

const deployTx = contract.deploy({

153

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

154

arguments: ['TokenName', 'TKN', 18] // Constructor arguments

155

});

156

157

// Send deployment transaction

158

const newContract = await deployTx.send({

159

from: '0x742C1382...',

160

gas: 2000000

161

});

162

163

console.log('Contract deployed at:', newContract.options.address);

164

165

// Estimate deployment gas

166

const deployGas = await deployTx.estimateGas({ from: '0x742C1382...' });

167

```

168

169

### Event Handling

170

171

Subscribe to contract events and retrieve historical event logs.

172

173

```typescript { .api }

174

interface ContractEvents<Abi extends ContractAbi> {

175

[eventName: string]: ContractEvent<any>;

176

177

allEvents(options?: EventOptions): EventEmitter;

178

}

179

180

interface ContractEvent<T> {

181

/**

182

* Subscribe to this event

183

* @param options - Event subscription options

184

* @returns Event emitter

185

*/

186

(options?: EventOptions): EventEmitter;

187

188

/**

189

* Get past events for this event type

190

* @param options - Event query options

191

* @returns Array of event logs

192

*/

193

getPastEvents(options?: EventOptions): Promise<EventLog<T>[]>;

194

}

195

196

/**

197

* Get past events for all event types or specific event

198

* @param eventName - Event name or 'allEvents'

199

* @param options - Event query options

200

* @returns Array of event logs

201

*/

202

getPastEvents(eventName: string, options?: EventOptions): Promise<EventLog[]>;

203

```

204

205

**Usage Examples:**

206

207

```typescript

208

// Subscribe to Transfer events

209

contract.events.Transfer({

210

filter: { from: '0x742C1382...' }

211

})

212

.on('data', (event) => {

213

console.log('Transfer event:', event.returnValues);

214

})

215

.on('error', console.error);

216

217

// Get past Transfer events

218

const pastEvents = await contract.getPastEvents('Transfer', {

219

filter: { from: '0x742C1382...' },

220

fromBlock: 0,

221

toBlock: 'latest'

222

});

223

224

// Subscribe to all events

225

contract.events.allEvents()

226

.on('data', (event) => {

227

console.log('Event:', event.event, event.returnValues);

228

});

229

```

230

231

### Contract Options Management

232

233

Manage contract instance configuration and provider settings.

234

235

```typescript { .api }

236

interface ContractOptions {

237

address?: Address;

238

jsonInterface: ContractAbi;

239

data?: string;

240

from?: Address;

241

gasPrice?: string;

242

maxFeePerGas?: string;

243

maxPriorityFeePerGas?: string;

244

gas?: number;

245

}

246

247

/**

248

* Contract options property

249

*/

250

options: ContractOptions;

251

252

/**

253

* Set new provider for the contract

254

* @param provider - New provider instance

255

*/

256

setProvider(provider: SupportedProviders): void;

257

258

/**

259

* Get current provider

260

*/

261

get currentProvider(): SupportedProviders | undefined;

262

```

263

264

**Usage Examples:**

265

266

```typescript

267

// Access contract options

268

console.log('Contract address:', contract.options.address);

269

console.log('Contract ABI:', contract.options.jsonInterface);

270

271

// Update contract options

272

contract.options.from = '0x742C1382...';

273

contract.options.gas = 200000;

274

275

// Change provider

276

contract.setProvider(new HttpProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'));

277

```

278

279

### Batch Contract Operations

280

281

Execute multiple contract calls in a single batch request.

282

283

```typescript { .api }

284

/**

285

* Create a batch request for multiple contract operations

286

*/

287

class ContractBatch {

288

constructor(contract: Contract);

289

290

/**

291

* Add a method call to the batch

292

* @param method - Contract method to call

293

* @returns Request object

294

*/

295

add(method: ContractMethod<any, any>): BatchRequest;

296

297

/**

298

* Execute all batched requests

299

* @returns Array of results

300

*/

301

execute(): Promise<any[]>;

302

}

303

```

304

305

## Types

306

307

```typescript { .api }

308

interface ContractAbi extends ReadonlyArray<AbiFragment> {}

309

310

interface AbiFragment {

311

type: 'function' | 'constructor' | 'event' | 'fallback' | 'receive';

312

name?: string;

313

inputs?: AbiInput[];

314

outputs?: AbiOutput[];

315

stateMutability?: 'pure' | 'view' | 'nonpayable' | 'payable';

316

anonymous?: boolean;

317

}

318

319

interface AbiInput {

320

name: string;

321

type: string;

322

indexed?: boolean;

323

components?: AbiInput[];

324

}

325

326

interface AbiOutput {

327

name: string;

328

type: string;

329

components?: AbiOutput[];

330

}

331

332

interface ContractInitOptions {

333

from?: Address;

334

gasPrice?: Numbers;

335

maxFeePerGas?: Numbers;

336

maxPriorityFeePerGas?: Numbers;

337

gas?: Numbers;

338

data?: string;

339

}

340

341

interface ContractDeployOptions {

342

data: string;

343

arguments?: any[];

344

}

345

346

interface EventOptions {

347

filter?: Record<string, any>;

348

fromBlock?: BlockNumberOrTag;

349

toBlock?: BlockNumberOrTag;

350

topics?: string[];

351

}

352

353

interface EventLog<T = any> {

354

event: string;

355

signature: string;

356

address: string;

357

returnValues: T;

358

logIndex: bigint;

359

transactionIndex: bigint;

360

transactionHash: string;

361

blockHash: string;

362

blockNumber: bigint;

363

raw: {

364

data: string;

365

topics: string[];

366

};

367

}

368

369

interface PayableCallOptions {

370

from?: Address;

371

gasPrice?: Numbers;

372

maxFeePerGas?: Numbers;

373

maxPriorityFeePerGas?: Numbers;

374

gas?: Numbers;

375

value?: Numbers;

376

}

377

378

interface PayableTxOptions extends PayableCallOptions {

379

nonce?: Numbers;

380

data?: string;

381

}

382

```