or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

contract-deployment.mdcontract-management.mdencoding-utilities.mdevent-handling.mdindex.mdmethod-execution.md

encoding-utilities.mddocs/

0

# Encoding and Utilities

1

2

Low-level encoding, decoding, and utility functions for contract interaction, address generation, and transaction parameter management.

3

4

## Capabilities

5

6

### Method Encoding/Decoding

7

8

Functions for encoding method calls and decoding return values.

9

10

```typescript { .api }

11

/**

12

* Encode method ABI with parameters for contract calls

13

* @param abi - The function or constructor fragment from contract ABI

14

* @param args - Arguments to encode

15

* @param deployData - Optional deployment bytecode for constructor calls

16

* @returns Encoded method call data as hex string

17

*/

18

function encodeMethodABI(

19

abi: AbiFunctionFragment | AbiConstructorFragment,

20

args: unknown[],

21

deployData?: HexString

22

): string;

23

24

/**

25

* Decode method parameters from transaction input data

26

* Alias for decodeFunctionCall from web3-eth-abi

27

* @param abi - The function fragment from contract ABI

28

* @param data - Encoded transaction input data

29

* @returns Decoded parameters object

30

*/

31

function decodeMethodParams(

32

abi: AbiFunctionFragment,

33

data: HexString

34

): DecodedParams & { __method__: string; __length__: number };

35

36

/**

37

* Decode method return values from transaction result

38

* Alias for decodeFunctionReturn from web3-eth-abi

39

* @param abi - The function fragment from contract ABI

40

* @param returnValues - Encoded return data

41

* @returns Decoded return values

42

*/

43

function decodeMethodReturn(

44

abi: AbiFunctionFragment,

45

returnValues: HexString

46

): unknown;

47

```

48

49

### Event Encoding/Decoding

50

51

Functions for encoding event filters and decoding event logs.

52

53

```typescript { .api }

54

/**

55

* Encode event ABI for log filtering

56

* @param abi - The event fragment from contract ABI

57

* @param options - Event filtering options

58

* @returns Encoded filter with topics and block range

59

*/

60

function encodeEventABI(

61

abi: AbiEventFragment,

62

options?: ContractEventOptions

63

): {

64

topics: Topic[];

65

fromBlock?: BlockNumberOrTag;

66

};

67

68

/**

69

* Decode event from log data (re-exported from web3-eth)

70

* @param abi - The event fragment or full ABI

71

* @param data - Log data to decode

72

* @param topics - Log topics array

73

* @param nonIndexedData - Non-indexed event data

74

* @returns Decoded event data

75

*/

76

function decodeEventABI(

77

abi: AbiEventFragment | ContractAbi,

78

data: LogsInput,

79

topics: string[],

80

nonIndexedData?: string

81

): EventLog;

82

```

83

84

### Address Generation

85

86

Utilities for generating contract addresses for deployment.

87

88

```typescript { .api }

89

/**

90

* Generate contract address using CREATE opcode (deterministic from deployer and nonce)

91

* @param from - Deployer address

92

* @param nonce - Transaction nonce

93

* @returns Computed contract address

94

*/

95

function createContractAddress(from: Address, nonce: Numbers): Address;

96

97

/**

98

* Generate contract address using CREATE2 opcode (deterministic from salt and init code)

99

* @param from - Deployer address

100

* @param salt - Salt value for CREATE2

101

* @param initCode - Contract initialization code

102

* @returns Computed CREATE2 contract address

103

*/

104

function create2ContractAddress(

105

from: Address,

106

salt: Bytes,

107

initCode: Bytes

108

): Address;

109

```

110

111

### Transaction Parameter Utilities

112

113

Internal utilities for preparing transaction parameters (exported for advanced usage).

114

115

```typescript { .api }

116

/**

117

* Get parameters for sending transactions

118

* @param options - Contract transaction options

119

* @param contractOptions - Contract default options

120

* @returns Formatted transaction parameters

121

*/

122

function getSendTxParams(options: {

123

options?: PayableCallOptions | NonPayableCallOptions;

124

contractOptions?: ContractOptions;

125

}): TransactionCall;

126

127

/**

128

* Get parameters for eth_call operations

129

* @param options - Contract call options

130

* @param contractOptions - Contract default options

131

* @returns Formatted call parameters

132

*/

133

function getEthTxCallParams(options: {

134

options?: PayableCallOptions | NonPayableCallOptions;

135

contractOptions?: ContractOptions;

136

}): TransactionCall;

137

138

/**

139

* Get parameters for gas estimation

140

* @param options - Contract gas estimation options

141

* @param contractOptions - Contract default options

142

* @returns Formatted gas estimation parameters

143

*/

144

function getEstimateGasParams(options: {

145

options?: PayableCallOptions | NonPayableCallOptions;

146

contractOptions?: ContractOptions;

147

}): TransactionCall;

148

149

/**

150

* Get parameters for access list creation

151

* @param options - Contract access list options

152

* @param contractOptions - Contract default options

153

* @returns Formatted access list parameters

154

*/

155

function getCreateAccessListParams(options: {

156

options?: PayableCallOptions | NonPayableCallOptions;

157

contractOptions?: ContractOptions;

158

}): TransactionForAccessList;

159

```

160

161

### Context Validation

162

163

Utility for validating Web3 contract context objects.

164

165

```typescript { .api }

166

/**

167

* Type guard to check if an object is a Web3ContractContext

168

* @param options - Object to check

169

* @returns True if object is Web3ContractContext

170

*/

171

function isWeb3ContractContext(options: unknown): options is Web3ContractContext;

172

```

173

174

## Usage Examples

175

176

### Method Encoding

177

178

```typescript

179

import { encodeMethodABI, decodeMethodParams, decodeMethodReturn } from "web3-eth-contract";

180

181

// Encode method call

182

const abi = {

183

inputs: [

184

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

185

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

186

],

187

name: "transfer",

188

outputs: [{ name: "", type: "bool" }],

189

stateMutability: "nonpayable",

190

type: "function"

191

} as const;

192

193

const encodedData = encodeMethodABI(

194

abi,

195

["0x1234567890123456789012345678901234567890", "1000000000000000000"]

196

);

197

console.log("Encoded method call:", encodedData);

198

// Output: 0xa9059cbb000000000000000000000000123456789012345678901234567890123456789000000000000000000000000000000000000000000000000000de0b6b3a7640000

199

200

// Decode method parameters from transaction input

201

const decodedParams = decodeMethodParams(abi, encodedData);

202

console.log("Decoded parameters:", {

203

to: decodedParams.to,

204

amount: decodedParams.amount,

205

method: decodedParams.__method__, // "transfer(address,uint256)"

206

length: decodedParams.__length__ // 2

207

});

208

209

// Decode method return values

210

const returnData = "0x0000000000000000000000000000000000000000000000000000000000000001";

211

const decodedReturn = decodeMethodReturn(abi, returnData);

212

console.log("Method returned:", decodedReturn); // true

213

```

214

215

### Event Encoding

216

217

```typescript

218

import { encodeEventABI, decodeEventABI } from "web3-eth-contract";

219

220

// Encode event filter

221

const eventAbi = {

222

anonymous: false,

223

inputs: [

224

{ indexed: true, name: "from", type: "address" },

225

{ indexed: true, name: "to", type: "address" },

226

{ indexed: false, name: "value", type: "uint256" }

227

],

228

name: "Transfer",

229

type: "event"

230

} as const;

231

232

const encodedFilter = encodeEventABI(eventAbi, {

233

filter: {

234

from: "0x1234567890123456789012345678901234567890",

235

to: ["0xabcd...", "0xefgh..."] // Multiple values

236

},

237

fromBlock: 1000000

238

});

239

240

console.log("Encoded filter:", {

241

topics: encodedFilter.topics,

242

fromBlock: encodedFilter.fromBlock

243

});

244

245

// Decode event from logs

246

const logData = {

247

address: "0x...",

248

topics: [

249

"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", // Transfer signature

250

"0x000000000000000000000000abcdefabcdefabcdefabcdefabcdefabcdefabcdef", // from

251

"0x000000000000000000000000123456789012345678901234567890123456789" // to

252

],

253

data: "0x00000000000000000000000000000000000000000000000000de0b6b3a7640000", // value

254

blockNumber: 1000001

255

};

256

257

const decodedEvent = decodeEventABI(eventAbi, logData, logData.topics);

258

console.log("Decoded event:", {

259

event: decodedEvent.event, // "Transfer"

260

from: decodedEvent.returnValues.from,

261

to: decodedEvent.returnValues.to,

262

value: decodedEvent.returnValues.value

263

});

264

```

265

266

### Contract Address Generation

267

268

```typescript

269

import { createContractAddress, create2ContractAddress } from "web3-eth-contract";

270

271

// Generate address for CREATE deployment

272

const deployerAddress = "0x1234567890123456789012345678901234567890";

273

const nonce = 42;

274

275

const contractAddress = createContractAddress(deployerAddress, nonce);

276

console.log("CREATE contract address:", contractAddress);

277

278

// Generate address for CREATE2 deployment

279

const salt = "0x0000000000000000000000000000000000000000000000000000000000000001";

280

const initCode = "0x608060405234801561001057600080fd5b50..."; // Contract bytecode + constructor args

281

282

const create2Address = create2ContractAddress(deployerAddress, salt, initCode);

283

console.log("CREATE2 contract address:", create2Address);

284

285

// Pre-compute address before deployment

286

console.log("Contract will be deployed at:", create2Address);

287

// Deploy and verify

288

const deployedContract = await contract.deploy({

289

data: initCode

290

}).send({ from: deployerAddress });

291

console.log("Actual deployed address:", deployedContract.options.address);

292

// Should match create2Address

293

```

294

295

### Advanced Transaction Parameter Handling

296

297

```typescript

298

import {

299

getSendTxParams,

300

getEstimateGasParams,

301

getCreateAccessListParams

302

} from "web3-eth-contract";

303

304

const contractOptions = {

305

from: "0x1234567890123456789012345678901234567890",

306

gas: 100000,

307

gasPrice: "20000000000"

308

};

309

310

const callOptions = {

311

from: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef",

312

gas: 150000,

313

value: "1000000000000000000" // 1 ETH

314

};

315

316

// Get parameters for sending transaction

317

const sendParams = getSendTxParams({

318

options: callOptions,

319

contractOptions

320

});

321

console.log("Send transaction params:", sendParams);

322

// Merged options with callOptions taking precedence

323

324

// Get parameters for gas estimation

325

const gasParams = getEstimateGasParams({

326

options: callOptions,

327

contractOptions

328

});

329

console.log("Gas estimation params:", gasParams);

330

331

// Get parameters for access list creation

332

const accessListParams = getCreateAccessListParams({

333

options: callOptions,

334

contractOptions

335

});

336

console.log("Access list params:", accessListParams);

337

```

338

339

### Context Validation

340

341

```typescript

342

import { isWeb3ContractContext } from "web3-eth-contract";

343

344

function handleContractInput(input: unknown) {

345

if (isWeb3ContractContext(input)) {

346

// TypeScript now knows input is Web3ContractContext

347

console.log("Provider:", input.provider);

348

console.log("Request manager:", input.requestManager);

349

console.log("Config:", input.config);

350

} else {

351

console.log("Not a valid Web3ContractContext");

352

}

353

}

354

355

// Test with various inputs

356

handleContractInput({

357

provider: web3Provider,

358

config: web3Config

359

}); // Valid context

360

361

handleContractInput({

362

from: "0x123...",

363

gas: 100000

364

}); // Not a context

365

```

366

367

### Low-Level Contract Interaction

368

369

```typescript

370

import {

371

encodeMethodABI,

372

createContractAddress,

373

getSendTxParams

374

} from "web3-eth-contract";

375

import { sendTransaction } from "web3-eth";

376

377

// Manual contract interaction without Contract class

378

async function manualContractCall() {

379

const methodAbi = {

380

inputs: [{ name: "value", type: "uint256" }],

381

name: "setValue",

382

outputs: [],

383

stateMutability: "nonpayable",

384

type: "function"

385

} as const;

386

387

// Encode method call

388

const encodedData = encodeMethodABI(methodAbi, [42]);

389

390

// Prepare transaction parameters

391

const txParams = getSendTxParams({

392

options: {

393

from: "0x1234567890123456789012345678901234567890",

394

to: "0xcontractaddress...",

395

data: encodedData,

396

gas: 100000

397

},

398

contractOptions: {}

399

});

400

401

// Send transaction using web3-eth directly

402

const receipt = await sendTransaction(web3, txParams);

403

console.log("Transaction sent:", receipt.transactionHash);

404

}

405

```

406

407

### Deployment Address Prediction

408

409

```typescript

410

import { createContractAddress, create2ContractAddress } from "web3-eth-contract";

411

412

class DeploymentPlanner {

413

private deployerAddress: string;

414

private currentNonce: number;

415

416

constructor(deployerAddress: string, currentNonce: number) {

417

this.deployerAddress = deployerAddress;

418

this.currentNonce = currentNonce;

419

}

420

421

predictNextContractAddress(): string {

422

return createContractAddress(this.deployerAddress, this.currentNonce);

423

}

424

425

predictContractAddressAtNonce(nonce: number): string {

426

return createContractAddress(this.deployerAddress, nonce);

427

}

428

429

predictCreate2Address(salt: string, initCode: string): string {

430

return create2ContractAddress(this.deployerAddress, salt, initCode);

431

}

432

433

planDeployments(contracts: Array<{ name: string; bytecode: string; salt?: string }>) {

434

const plan = contracts.map((contract, index) => {

435

const address = contract.salt

436

? this.predictCreate2Address(contract.salt, contract.bytecode)

437

: this.predictContractAddressAtNonce(this.currentNonce + index);

438

439

return {

440

name: contract.name,

441

predictedAddress: address,

442

deploymentMethod: contract.salt ? 'CREATE2' : 'CREATE'

443

};

444

});

445

446

console.log("Deployment plan:", plan);

447

return plan;

448

}

449

}

450

451

// Usage

452

const planner = new DeploymentPlanner(

453

"0x1234567890123456789012345678901234567890",

454

await web3.eth.getTransactionCount("0x1234567890123456789012345678901234567890")

455

);

456

457

const deploymentPlan = planner.planDeployments([

458

{ name: "Token", bytecode: tokenBytecode },

459

{ name: "Exchange", bytecode: exchangeBytecode, salt: "0x01" }

460

]);

461

```