CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-typechain

TypeScript bindings generator for Ethereum smart contracts that transforms ABI files into type-safe interfaces and classes

Pending
Overview
Eval results
Files

cli-interface.mddocs/

CLI Interface

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

Capabilities

Argument Parsing

parseArgs Function

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

/**
 * Parses command-line arguments using ts-command-line-args
 * @returns Parsed configuration object with all CLI options
 */
function parseArgs(): ParsedArgs;

ParsedArgs Interface

Configuration object returned by CLI argument parsing.

interface ParsedArgs {
  /** Array of file patterns to process (default: "**/*.abi") */
  files: string[];
  /** Target code generator (ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1, or custom path) */
  target: string;
  /** Optional output directory for generated files */
  outDir?: string;
  /** Optional input directory containing ABI files */
  inputDir?: string;
  /** Configuration flags object */
  flags: {
    /** Add artificial contractName field for type discrimination */
    discriminateTypes: boolean;
    /** Force generation of overloaded functions even when not needed */
    alwaysGenerateOverloads: boolean;
    /** Add @ts-nocheck comment to generated files */
    tsNocheck: boolean;
    /** Add .js extension for Node ESM module support */
    node16Modules: boolean;
  };
}

Command Usage

Basic Command Syntax

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

Command Line Options

Positional Arguments:

  • glob (multiple): File patterns to process
    • Default: "**/*.abi"
    • Examples: "./artifacts/**/*.json", "./contracts/*.abi"

Required Options:

  • --target <target>: Target generator
    • Built-in targets: ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1
    • Custom targets: Path to custom target module

Optional Options:

  • --out-dir <dir>: Output directory for generated files
  • --input-dir <dir>: Input directory containing ABI files
  • --always-generate-overloads: Force generation of overloaded functions
  • --ts-nocheck: Add @ts-nocheck to generated files
  • --discriminate-types: Add contractName field for type discrimination
  • --node16-modules: Add .js extension for Node ESM support
  • --show-stack-traces: Show full stack traces on error
  • --help, -h: Display help information

Usage Examples:

# Basic usage with ethers-v5 target
typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/**/*.json'

# Multiple glob patterns
typechain --target ethers-v5 './artifacts/**/*.json' './contracts/*.abi'

# With additional options
typechain \
  --target ethers-v5 \
  --out-dir ./typechain-types \
  --always-generate-overloads \
  --discriminate-types \
  './artifacts/contracts/**/*.sol/*.json'

# Using input directory (alternative to glob patterns)
typechain --target ethers-v5 --input-dir ./artifacts --out-dir ./typechain-types

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

# Development mode with type discrimination
typechain --target ethers-v5 --discriminate-types --ts-nocheck --out-dir ./typechain-types './artifacts/**/*.json'

CLI Workflow

Main CLI Entry Point

The CLI follows this workflow:

  1. Parse Arguments: Uses parseArgs() to process command-line options
  2. Resolve File Patterns: Uses glob() to resolve file patterns to actual files
  3. Create Configuration: Builds complete Config object from parsed arguments
  4. Run TypeChain: Calls runTypeChain() to generate TypeScript bindings
  5. Output Results: Displays success message with file count
// CLI workflow (simplified)
import { parseArgs } from "./parseArgs";
import { glob } from "../utils/glob";
import { runTypeChain } from "../typechain/runTypeChain";

async function main() {
  try {
    // Parse command line arguments
    const args = parseArgs();
    
    // Resolve file patterns to actual files
    const allFiles = glob(process.cwd(), args.files);
    
    // Create configuration
    const config = {
      cwd: process.cwd(),
      target: args.target,
      outDir: args.outDir,
      inputDir: args.inputDir,
      filesToProcess: allFiles,
      allFiles: allFiles,
      flags: args.flags
    };
    
    // Generate TypeScript bindings
    const result = await runTypeChain(config);
    
    // Output success message
    console.log(`Successfully generated ${result.filesGenerated} files`);
  } catch (error) {
    console.error("TypeChain error:", error.message);
    if (args.showStackTraces) {
      console.error(error.stack);
    }
    process.exit(1);
  }
}

Target Specifications

Built-in Targets

TypeChain includes several built-in target generators:

ethers-v4: Generates bindings for ethers.js v4

  • Creates contract interfaces and typed method signatures
  • Supports event filtering and listening
  • Compatible with ethers v4 provider system

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

  • Full TypeScript support with generics
  • Improved type safety and error handling
  • Supports all ethers v5 features including contract factories

truffle-v4: Generates bindings for Truffle contracts v4

  • Compatible with Truffle's contract abstraction
  • Supports migration and deployment helpers
  • Legacy support for older Truffle projects

truffle-v5: Generates bindings for Truffle contracts v5

  • Updated for Truffle v5 contract system
  • Better TypeScript integration
  • Supports modern Truffle features

web3-v1: Generates bindings for web3.js v1

  • Compatible with web3 1.x contract system
  • Supports method calls and event subscriptions
  • Full coverage of web3 contract API

Custom Targets

You can specify custom target generators by providing a path:

# Using a custom target module
typechain --target ./custom-targets/my-target.js './artifacts/**/*.json'

# Using an npm package target
typechain --target @mycompany/typechain-target './artifacts/**/*.json'

Custom targets must export a class extending TypeChainTarget:

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

export default class MyCustomTarget extends TypeChainTarget {
  readonly name = "my-custom-target";
  
  transformFile(file: FileDescription): FileDescription[] {
    const contract = this.parseContract(file);
    return [{
      path: `${contract.name}.ts`,
      contents: this.generateBinding(contract)
    }];
  }
}

Configuration Files

Package.json Scripts

Typical package.json integration:

{
  "scripts": {
    "typechain": "typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'",
    "build": "hardhat compile && npm run typechain"
  }
}

Hardhat Integration

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

# After Hardhat compilation
npx hardhat compile
npx typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'

Error Handling

Common CLI Errors

Target Not Found:

Error: Cannot find target "invalid-target"
Available targets: ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1

No Files Found:

Error: No files found matching pattern './artifacts/**/*.json'
Check your glob pattern and ensure ABI files exist

Invalid ABI:

Error: Malformed ABI in file './contracts/Invalid.json'
JSON parsing failed: Unexpected token

Permission Errors:

Error: EACCES: permission denied, mkdir './protected-dir'
Check write permissions for output directory

Debug Mode

Enable detailed logging for troubleshooting:

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

This will output detailed information about:

  • File discovery and filtering
  • ABI parsing steps
  • Code generation progress
  • Output file writing

Stack Traces

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

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

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

Integration Examples

CI/CD Integration

GitHub Actions workflow:

name: Generate TypeChain Bindings
on: [push, pull_request]

jobs:
  typechain:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '16'
      - run: npm ci
      - run: npx hardhat compile
      - run: npx typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'
      - run: npm run test

Build Tools Integration

With webpack or other bundlers:

// webpack.config.js
const { spawn } = require('child_process');

module.exports = {
  // ... other config
  plugins: [
    {
      apply: (compiler) => {
        compiler.hooks.beforeCompile.tapAsync('TypeChain', (params, callback) => {
          const typechain = spawn('npx', [
            'typechain',
            '--target', 'ethers-v5',
            '--out-dir', './typechain-types',
            './artifacts/**/*.json'
          ]);
          
          typechain.on('close', (code) => {
            if (code === 0) {
              callback();
            } else {
              callback(new Error('TypeChain generation failed'));
            }
          });
        });
      }
    }
  ]
};

Install with Tessl CLI

npx tessl i tessl/npm-typechain

docs

abi-parsing.md

cli-interface.md

code-generation.md

core-api.md

file-utilities.md

index.md

types-interfaces.md

tile.json