TypeScript bindings generator for Ethereum smart contracts that transforms ABI files into type-safe interfaces and classes
—
Command-line interface for running TypeChain with extensive configuration options and file pattern matching.
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;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;
};
}typechain [glob ...] --target <target> [options]Positional Arguments:
glob (multiple): File patterns to process
"**/*.abi""./artifacts/**/*.json", "./contracts/*.abi"Required Options:
--target <target>: Target generator
ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1Optional 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 informationUsage 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'The CLI follows this workflow:
parseArgs() to process command-line optionsglob() to resolve file patterns to actual filesConfig object from parsed argumentsrunTypeChain() to generate TypeScript bindings// 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);
}
}TypeChain includes several built-in target generators:
ethers-v4: Generates bindings for ethers.js v4
ethers-v5: Generates bindings for ethers.js v5 (recommended)
truffle-v4: Generates bindings for Truffle contracts v4
truffle-v5: Generates bindings for Truffle contracts v5
web3-v1: Generates bindings for web3.js v1
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)
}];
}
}Typical package.json integration:
{
"scripts": {
"typechain": "typechain --target ethers-v5 --out-dir ./typechain-types './artifacts/contracts/**/*.sol/*.json'",
"build": "hardhat compile && npm run typechain"
}
}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'Target Not Found:
Error: Cannot find target "invalid-target"
Available targets: ethers-v4, ethers-v5, truffle-v4, truffle-v5, web3-v1No Files Found:
Error: No files found matching pattern './artifacts/**/*.json'
Check your glob pattern and ensure ABI files existInvalid ABI:
Error: Malformed ABI in file './contracts/Invalid.json'
JSON parsing failed: Unexpected tokenPermission Errors:
Error: EACCES: permission denied, mkdir './protected-dir'
Check write permissions for output directoryEnable detailed logging for troubleshooting:
DEBUG=typechain* typechain --target ethers-v5 './artifacts/**/*.json'This will output detailed information about:
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.
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 testWith 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