or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

abi-parsing.mdcli-interface.mdcode-generation.mdcore-api.mdfile-utilities.mdindex.mdtypes-interfaces.md

code-generation.mddocs/

0

# Code Generation

1

2

Tools for generating TypeScript code including barrel files, imports, and syntax utilities for TypeChain targets.

3

4

## Capabilities

5

6

### Barrel Files

7

8

#### createBarrelFiles Function

9

10

Generates barrel files with re-exports for all given paths (implements barrel pattern).

11

12

```typescript { .api }

13

/**

14

* Generates barrel files with re-exports for all given paths

15

* @param paths - Array of file paths to create barrels for

16

* @param options - Configuration for barrel generation

17

* @returns Array of file descriptions for generated barrel files

18

*/

19

function createBarrelFiles(

20

paths: string[],

21

options: {

22

/** Whether to generate type-only exports */

23

typeOnly: boolean;

24

/** Optional postfix to add to export names */

25

postfix?: string;

26

/** Optional suffix to add to module imports */

27

moduleSuffix?: string;

28

}

29

): FileDescription[];

30

31

interface FileDescription {

32

/** File path for the generated barrel file */

33

path: string;

34

/** TypeScript content for the barrel file */

35

contents: string;

36

}

37

```

38

39

**Usage Example:**

40

41

```typescript

42

import { createBarrelFiles } from "typechain";

43

44

// Generate barrel files for contract bindings

45

const contractPaths = [

46

"./typechain-types/MyToken.ts",

47

"./typechain-types/MyNFT.ts",

48

"./typechain-types/factories/MyToken__factory.ts"

49

];

50

51

const barrelFiles = createBarrelFiles(contractPaths, {

52

typeOnly: false,

53

postfix: "__factory",

54

moduleSuffix: ".js"

55

});

56

57

// Result: barrel files with re-exports like:

58

// export { MyToken } from "./MyToken.js";

59

// export { MyToken__factory } from "./factories/MyToken__factory.js";

60

```

61

62

### Syntax Utilities

63

64

#### createPositionalIdentifier Function

65

66

Creates an identifier prefixing reserved words with underscore.

67

68

```typescript { .api }

69

/**

70

* Creates an identifier prefixing reserved words with underscore

71

* Used for function parameters and tuple element names

72

* @param identifierName - Original identifier name

73

* @returns Safe identifier name for TypeScript

74

* @internal

75

*/

76

function createPositionalIdentifier(identifierName: string): string;

77

```

78

79

#### getUsedIdentifiers Function

80

81

Returns list of identifiers that are used in the source file.

82

83

```typescript { .api }

84

/**

85

* Returns list of identifiers that are used in the source file

86

* @param identifiers - Array of potential identifiers to check

87

* @param sourceFile - TypeScript source code to scan

88

* @returns Array of identifiers actually used in the source

89

* @internal

90

*/

91

function getUsedIdentifiers(identifiers: string[], sourceFile: string): string[];

92

```

93

94

### Import Generation

95

96

#### createImportTypeDeclaration Function

97

98

Creates TypeScript import type declaration.

99

100

```typescript { .api }

101

/**

102

* Creates TypeScript import type declaration

103

* @param identifiers - Array of type identifiers to import

104

* @param moduleSpecifier - Module path to import from

105

* @returns TypeScript import type statement

106

* @internal

107

*/

108

function createImportTypeDeclaration(identifiers: string[], moduleSpecifier: string): string;

109

```

110

111

#### createImportsForUsedIdentifiers Function

112

113

Creates import statements for identifiers actually used in source file.

114

115

```typescript { .api }

116

/**

117

* Creates import statements for identifiers actually used in source file

118

* @param possibleImports - Map of module specifiers to available identifiers

119

* @param sourceFile - TypeScript source code to analyze

120

* @returns Generated import statements

121

* @internal

122

*/

123

function createImportsForUsedIdentifiers(

124

possibleImports: Record<ModuleSpecifier, Identifier[]>,

125

sourceFile: string

126

): string;

127

128

type ModuleSpecifier = string;

129

type Identifier = string;

130

```

131

132

### Directory Normalization

133

134

#### normalizeDirName Function

135

136

Converts valid directory name to valid variable name.

137

138

```typescript { .api }

139

/**

140

* Converts valid directory name to valid variable name

141

* @param rawName - Directory name (e.g., "0directory-name")

142

* @returns Valid JavaScript identifier (e.g., "_0DirectoryName")

143

*/

144

function normalizeDirName(rawName: string): string;

145

```

146

147

**Usage Example:**

148

149

```typescript

150

import { normalizeDirName } from "typechain";

151

152

const normalized = normalizeDirName("0my-contract");

153

// Result: "_0MyContract"

154

155

const normalized2 = normalizeDirName("special-contracts");

156

// Result: "SpecialContracts"

157

```

158

159

### Output Transformers

160

161

#### OutputTransformer Type

162

163

Function type for output transformers that process generated code.

164

165

```typescript { .api }

166

/**

167

* Function type for output transformers

168

* @param output - Generated TypeScript code

169

* @param services - External services (fs, prettier, etc.)

170

* @param cfg - TypeChain configuration

171

* @returns Transformed output code

172

*/

173

type OutputTransformer = (output: string, services: Services, cfg: Config) => string;

174

175

interface Services {

176

fs: typeof fs;

177

prettier: typeof prettier;

178

mkdirp: typeof mkdirp;

179

}

180

181

interface Config {

182

cwd: string;

183

target: string;

184

outDir?: string;

185

prettier?: object;

186

filesToProcess: string[];

187

allFiles: string[];

188

inputDir: string;

189

flags: CodegenConfig;

190

}

191

```

192

193

#### outputTransformers Array

194

195

Array of output transformer functions applied to generated code.

196

197

```typescript { .api }

198

/**

199

* Array of output transformer functions applied to generated code

200

* Transformers are applied in order to process and format output

201

*/

202

const outputTransformers: OutputTransformer[];

203

```

204

205

#### prettierOutputTransformer

206

207

Applies prettier formatting to generated TypeScript code.

208

209

```typescript { .api }

210

/**

211

* Applies prettier formatting to generated TypeScript code

212

* Uses prettier configuration from project or default TypeScript settings

213

*/

214

const prettierOutputTransformer: OutputTransformer;

215

```

216

217

#### addPreambleOutputTransformer

218

219

Adds standard preamble to generated files.

220

221

```typescript { .api }

222

/**

223

* Adds standard preamble to generated files

224

* Includes autogenerated comment, linting disables, optional @ts-nocheck

225

*/

226

const addPreambleOutputTransformer: OutputTransformer;

227

```

228

229

**Generated Preamble Example:**

230

231

```typescript

232

/* Autogenerated file. Do not edit manually. */

233

/* tslint:disable */

234

/* eslint-disable */

235

// @ts-nocheck (if cfg.flags.tsNocheck is true)

236

237

// Generated TypeScript bindings follow...

238

```

239

240

### Code Generation Templates

241

242

#### Template System Usage

243

244

While the template system is internal to target implementations, here's how code generation typically works:

245

246

```typescript

247

// Example of how targets use the code generation utilities

248

import {

249

createBarrelFiles,

250

createImportsForUsedIdentifiers,

251

normalizeDirName

252

} from "typechain";

253

254

class EthersV5Target extends TypeChainTarget {

255

transformFile(file: FileDescription): FileDescription[] {

256

const contract = parse(extractAbi(file.contents), file.path);

257

258

// Generate main contract binding

259

const contractFile = {

260

path: `${contract.name}.ts`,

261

contents: this.generateContractBinding(contract)

262

};

263

264

// Generate factory

265

const factoryFile = {

266

path: `factories/${contract.name}__factory.ts`,

267

contents: this.generateFactory(contract)

268

};

269

270

return [contractFile, factoryFile];

271

}

272

273

afterRun(): FileDescription[] {

274

// Generate barrel files for all contracts

275

return createBarrelFiles(this.generatedFiles, {

276

typeOnly: false,

277

moduleSuffix: this.cfg.flags.node16Modules ? '.js' : undefined

278

});

279

}

280

}

281

```

282

283

### File Organization

284

285

#### File Path Utilities

286

287

Functions for organizing generated files:

288

289

```typescript { .api }

290

/**

291

* Generate appropriate file path for contract binding

292

* @param contract - Parsed contract object

293

* @param target - Target generator name

294

* @param options - Path generation options

295

* @returns Relative file path for the binding

296

*/

297

function generateContractFilePath(

298

contract: Contract,

299

target: string,

300

options?: { includeFactories?: boolean }

301

): string;

302

303

/**

304

* Generate appropriate file path for factory binding

305

* @param contract - Parsed contract object

306

* @param target - Target generator name

307

* @returns Relative file path for the factory

308

*/

309

function generateFactoryFilePath(contract: Contract, target: string): string;

310

```

311

312

### Code Quality

313

314

#### Linting and Formatting

315

316

Generated code includes standard quality measures:

317

318

- **ESLint disable comments**: Prevents linting errors on generated code

319

- **TSLint disable comments**: For legacy TSLint compatibility

320

- **Prettier formatting**: Consistent code formatting

321

- **Optional @ts-nocheck**: Skips TypeScript checking if configured

322

323

#### Generated Code Structure

324

325

Typical structure of generated TypeScript files:

326

327

```typescript

328

/* Autogenerated file. Do not edit manually. */

329

/* tslint:disable */

330

/* eslint-disable */

331

332

import type { BaseContract, BigNumber, Signer, utils } from "ethers";

333

334

export interface MyTokenInterface extends utils.Interface {

335

functions: {

336

"transfer(address,uint256)": FunctionFragment;

337

// ... other functions

338

};

339

340

getFunction(nameOrSignatureOrTopic: "transfer"): FunctionFragment;

341

// ... other methods

342

}

343

344

export interface MyToken extends BaseContract {

345

interface: MyTokenInterface;

346

347

transfer(to: string, value: BigNumber): Promise<ContractTransaction>;

348

// ... other methods

349

}

350

```