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

cli-interface.mddocs/

0

# CLI Interface

1

2

Command-line interface for running TypeChain with extensive configuration options and file pattern matching.

3

4

## Capabilities

5

6

### Argument Parsing

7

8

#### parseArgs Function

9

10

Parses command-line arguments using ts-command-line-args.

11

12

```typescript { .api }

13

/**

14

* Parses command-line arguments using ts-command-line-args

15

* @returns Parsed configuration object with all CLI options

16

*/

17

function parseArgs(): ParsedArgs;

18

```

19

20

#### ParsedArgs Interface

21

22

Configuration object returned by CLI argument parsing.

23

24

```typescript { .api }

25

interface ParsedArgs {

26

/** Array of file patterns to process (default: "**/*.abi") */

27

files: string[];

28

/** Target code generator (ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1, or custom path) */

29

target: string;

30

/** Optional output directory for generated files */

31

outDir?: string;

32

/** Optional input directory containing ABI files */

33

inputDir?: string;

34

/** Configuration flags object */

35

flags: {

36

/** Add artificial contractName field for type discrimination */

37

discriminateTypes: boolean;

38

/** Force generation of overloaded functions even when not needed */

39

alwaysGenerateOverloads: boolean;

40

/** Add @ts-nocheck comment to generated files */

41

tsNocheck: boolean;

42

/** Add .js extension for Node ESM module support */

43

node16Modules: boolean;

44

};

45

}

46

```

47

48

### Command Usage

49

50

#### Basic Command Syntax

51

52

```bash

53

typechain [glob ...] --target <target> [options]

54

```

55

56

#### Command Line Options

57

58

**Positional Arguments:**

59

- `glob` (multiple): File patterns to process

60

- Default: `"**/*.abi"`

61

- Examples: `"./artifacts/**/*.json"`, `"./contracts/*.abi"`

62

63

**Required Options:**

64

- `--target <target>`: Target generator

65

- Built-in targets: `ethers-v4`, `ethers-v5`, `truffle-v4`, `truffle-v5`, `web3-v1`

66

- Custom targets: Path to custom target module

67

68

**Optional Options:**

69

- `--out-dir <dir>`: Output directory for generated files

70

- `--input-dir <dir>`: Input directory containing ABI files

71

- `--always-generate-overloads`: Force generation of overloaded functions

72

- `--ts-nocheck`: Add @ts-nocheck to generated files

73

- `--discriminate-types`: Add contractName field for type discrimination

74

- `--node16-modules`: Add .js extension for Node ESM support

75

- `--show-stack-traces`: Show full stack traces on error

76

- `--help, -h`: Display help information

77

78

**Usage Examples:**

79

80

```bash

81

# Basic usage with ethers-v5 target

82

typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/**/*.json'

83

84

# Multiple glob patterns

85

typechain --target ethers-v5 './artifacts/**/*.json' './contracts/*.abi'

86

87

# With additional options

88

typechain \

89

--target ethers-v5 \

90

--out-dir ./typechain-types \

91

--always-generate-overloads \

92

--discriminate-types \

93

'./artifacts/contracts/**/*.sol/*.json'

94

95

# Using input directory (alternative to glob patterns)

96

typechain --target ethers-v5 --input-dir ./artifacts --out-dir ./typechain-types

97

98

# Node ESM support

99

typechain --target ethers-v5 --node16-modules --out-dir ./typechain-types './artifacts/**/*.json'

100

101

# Development mode with type discrimination

102

typechain --target ethers-v5 --discriminate-types --ts-nocheck --out-dir ./typechain-types './artifacts/**/*.json'

103

```

104

105

### CLI Workflow

106

107

#### Main CLI Entry Point

108

109

The CLI follows this workflow:

110

111

1. **Parse Arguments**: Uses `parseArgs()` to process command-line options

112

2. **Resolve File Patterns**: Uses `glob()` to resolve file patterns to actual files

113

3. **Create Configuration**: Builds complete `Config` object from parsed arguments

114

4. **Run TypeChain**: Calls `runTypeChain()` to generate TypeScript bindings

115

5. **Output Results**: Displays success message with file count

116

117

```typescript

118

// CLI workflow (simplified)

119

import { parseArgs } from "./parseArgs";

120

import { glob } from "../utils/glob";

121

import { runTypeChain } from "../typechain/runTypeChain";

122

123

async function main() {

124

try {

125

// Parse command line arguments

126

const args = parseArgs();

127

128

// Resolve file patterns to actual files

129

const allFiles = glob(process.cwd(), args.files);

130

131

// Create configuration

132

const config = {

133

cwd: process.cwd(),

134

target: args.target,

135

outDir: args.outDir,

136

inputDir: args.inputDir,

137

filesToProcess: allFiles,

138

allFiles: allFiles,

139

flags: args.flags

140

};

141

142

// Generate TypeScript bindings

143

const result = await runTypeChain(config);

144

145

// Output success message

146

console.log(`Successfully generated ${result.filesGenerated} files`);

147

} catch (error) {

148

console.error("TypeChain error:", error.message);

149

if (args.showStackTraces) {

150

console.error(error.stack);

151

}

152

process.exit(1);

153

}

154

}

155

```

156

157

### Target Specifications

158

159

#### Built-in Targets

160

161

TypeChain includes several built-in target generators:

162

163

**ethers-v4**: Generates bindings for ethers.js v4

164

- Creates contract interfaces and typed method signatures

165

- Supports event filtering and listening

166

- Compatible with ethers v4 provider system

167

168

**ethers-v5**: Generates bindings for ethers.js v5 (recommended)

169

- Full TypeScript support with generics

170

- Improved type safety and error handling

171

- Supports all ethers v5 features including contract factories

172

173

**truffle-v4**: Generates bindings for Truffle contracts v4

174

- Compatible with Truffle's contract abstraction

175

- Supports migration and deployment helpers

176

- Legacy support for older Truffle projects

177

178

**truffle-v5**: Generates bindings for Truffle contracts v5

179

- Updated for Truffle v5 contract system

180

- Better TypeScript integration

181

- Supports modern Truffle features

182

183

**web3-v1**: Generates bindings for web3.js v1

184

- Compatible with web3 1.x contract system

185

- Supports method calls and event subscriptions

186

- Full coverage of web3 contract API

187

188

#### Custom Targets

189

190

You can specify custom target generators by providing a path:

191

192

```bash

193

# Using a custom target module

194

typechain --target ./custom-targets/my-target.js './artifacts/**/*.json'

195

196

# Using an npm package target

197

typechain --target @mycompany/typechain-target './artifacts/**/*.json'

198

```

199

200

Custom targets must export a class extending `TypeChainTarget`:

201

202

```typescript

203

import { TypeChainTarget, Contract, FileDescription } from "typechain";

204

205

export default class MyCustomTarget extends TypeChainTarget {

206

readonly name = "my-custom-target";

207

208

transformFile(file: FileDescription): FileDescription[] {

209

const contract = this.parseContract(file);

210

return [{

211

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

212

contents: this.generateBinding(contract)

213

}];

214

}

215

}

216

```

217

218

### Configuration Files

219

220

#### Package.json Scripts

221

222

Typical package.json integration:

223

224

```json

225

{

226

"scripts": {

227

"typechain": "typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'",

228

"build": "hardhat compile && npm run typechain"

229

}

230

}

231

```

232

233

#### Hardhat Integration

234

235

With Hardhat, TypeChain is often used as part of the compilation process:

236

237

```bash

238

# After Hardhat compilation

239

npx hardhat compile

240

npx typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'

241

```

242

243

### Error Handling

244

245

#### Common CLI Errors

246

247

**Target Not Found:**

248

```bash

249

Error: Cannot find target "invalid-target"

250

Available targets: ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1

251

```

252

253

**No Files Found:**

254

```bash

255

Error: No files found matching pattern './artifacts/**/*.json'

256

Check your glob pattern and ensure ABI files exist

257

```

258

259

**Invalid ABI:**

260

```bash

261

Error: Malformed ABI in file './contracts/Invalid.json'

262

JSON parsing failed: Unexpected token

263

```

264

265

**Permission Errors:**

266

```bash

267

Error: EACCES: permission denied, mkdir './protected-dir'

268

Check write permissions for output directory

269

```

270

271

#### Debug Mode

272

273

Enable detailed logging for troubleshooting:

274

275

```bash

276

DEBUG=typechain* typechain --target ethers-v5 './artifacts/**/*.json'

277

```

278

279

This will output detailed information about:

280

- File discovery and filtering

281

- ABI parsing steps

282

- Code generation progress

283

- Output file writing

284

285

#### Stack Traces

286

287

For development and debugging, use `--show-stack-traces`:

288

289

```bash

290

typechain --target ethers-v5 --show-stack-traces './artifacts/**/*.json'

291

```

292

293

This provides full error stack traces instead of simplified error messages.

294

295

### Integration Examples

296

297

#### CI/CD Integration

298

299

GitHub Actions workflow:

300

301

```yaml

302

name: Generate TypeChain Bindings

303

on: [push, pull_request]

304

305

jobs:

306

typechain:

307

runs-on: ubuntu-latest

308

steps:

309

- uses: actions/checkout@v2

310

- uses: actions/setup-node@v2

311

with:

312

node-version: '16'

313

- run: npm ci

314

- run: npx hardhat compile

315

- run: npx typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'

316

- run: npm run test

317

```

318

319

#### Build Tools Integration

320

321

With webpack or other bundlers:

322

323

```javascript

324

// webpack.config.js

325

const { spawn } = require('child_process');

326

327

module.exports = {

328

// ... other config

329

plugins: [

330

{

331

apply: (compiler) => {

332

compiler.hooks.beforeCompile.tapAsync('TypeChain', (params, callback) => {

333

const typechain = spawn('npx', [

334

'typechain',

335

'--target', 'ethers-v5',

336

'--out-dir', './typechain-types',

337

'./artifacts/**/*.json'

338

]);

339

340

typechain.on('close', (code) => {

341

if (code === 0) {

342

callback();

343

} else {

344

callback(new Error('TypeChain generation failed'));

345

}

346

});

347

});

348

}

349

}

350

]

351

};

352

```