### Run the project Source: https://github.com/dethcrypto/typechain/blob/master/examples/ethers-v6/README.md Install dependencies to trigger type generation and start the project. ```sh pnpm install # it will automatically run TypeChain types generation # pnpm generate-types to manually regenerate them pnpm start ``` -------------------------------- ### Install Dependencies and Run Example Source: https://github.com/dethcrypto/typechain/blob/master/examples/ethers-v5-nodenext/README.md Install project dependencies, which automatically triggers TypeChain type generation. Alternatively, use 'pnpm generate-types' to regenerate them manually. Then, start the application. ```sh pnpm install # pnpm generate-types to manually regenerate them pnpm start ``` -------------------------------- ### Install and Build Monorepo Source: https://github.com/dethcrypto/typechain/blob/master/examples/web3-v1/README.md Run these commands in the root of the monorepo to install dependencies and build the project before running the example. ```sh pnpm install pnpm build ``` -------------------------------- ### Build Monorepo Source: https://github.com/dethcrypto/typechain/blob/master/examples/ethers-v5-nodenext/README.md Run these commands in the root of the monorepo to install dependencies and build the project before running the example. ```sh pnpm i pnpm build ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Installs all project dependencies using pnpm. Ensure pnpm version 7 is installed. ```sh pnpm i ``` -------------------------------- ### CLI Options Reference Example Source: https://context7.com/dethcrypto/typechain/llms.txt Demonstrates the usage of TypeChain CLI with all available options for comprehensive configuration. ```bash typechain \ --target ethers-v6 \ --out-dir ./src/types \ --input-dir ./abis \ --always-generate-overloads \ --discriminate-types \ --node16-modules \ './abis/**/*.json' ``` -------------------------------- ### Build the monorepo Source: https://github.com/dethcrypto/typechain/blob/master/examples/hardhat-truffe-v5/README.md Required initialization steps to build the monorepo before running examples. ```sh # in the root of monorepo pnpm install pnpm build ``` -------------------------------- ### Build the monorepo Source: https://github.com/dethcrypto/typechain/blob/master/examples/ethers-v6/README.md Install dependencies and build the monorepo from the root directory. ```sh # in the root of monorepo pnpm i pnpm build ``` -------------------------------- ### Install Dependencies and Generate Types Source: https://github.com/dethcrypto/typechain/blob/master/examples/hardhat/README.md Install project dependencies. This command automatically runs TypeChain type generation. Use 'pnpm generate-types' to regenerate manually. ```sh pnpm install # pnpm generate-types to manually regenerate them pnpm test ``` -------------------------------- ### Install TypeChain dependencies for Truffle Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Install the necessary packages for Truffle-based projects. ```bash npm install --save-dev typechain @typechain/hardhat @typechain/truffle-v5 ``` -------------------------------- ### Install TypeChain dependencies for Ethers Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Install the necessary packages for Ethers-based projects. ```bash npm install --save-dev typechain @typechain/hardhat @typechain/ethers-v6 ``` -------------------------------- ### Run project commands Source: https://github.com/dethcrypto/typechain/blob/master/examples/truffle-v5/README.md Commands for installing dependencies, generating types, running tests, and executing migrations. ```sh pnpm install # it will automatically run TypeChain types generation # pnpm generate-types to manually regenerate them # run tests truffle test # migrations are kinda tricky (look at known limitation section) - we need to transpile ts to js file (this is not a case for tests) pnpm migrate ``` -------------------------------- ### Run project tests Source: https://github.com/dethcrypto/typechain/blob/master/examples/hardhat-truffe-v5/README.md Commands to install dependencies, generate types, and execute tests. ```sh pnpm install # it will automatically run TypeChain types generation # pnpm generate-types to manually regenerate them pnpm test ``` -------------------------------- ### Install TypeChain with Target Packages Source: https://context7.com/dethcrypto/typechain/llms.txt Install TypeChain with the appropriate target package for your blockchain library. Use npm install --save-dev to add typechain and the desired target. ```bash # For Ethers.js v6 (recommended) npm install --save-dev typechain @typechain/ethers-v6 # For Ethers.js v5 npm install --save-dev typechain @typechain/ethers-v5 # For Web3.js v1 npm install --save-dev typechain @typechain/web3-v1 # For Truffle v5 npm install --save-dev typechain @typechain/truffle-v5 # For Hardhat with Ethers.js v6 npm install --save-dev typechain @typechain/hardhat @typechain/ethers-v6 # For Hardhat with Truffle v5 npm install --save-dev typechain @typechain/hardhat @typechain/truffle-v5 # For Starknet.js npm install --save-dev typechain @typechain/starknet ``` -------------------------------- ### Sample tsconfig.json configuration Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Example TypeScript configuration file for projects using TypeChain. ```json { "compilerOptions": { "target": "es2018", "module": "commonjs", "strict": true, "esModuleInterop": true, "outDir": "dist", "resolveJsonModule": true }, "include": ["./scripts", "./test", "./typechain-types"], "files": ["./hardhat.config.ts"] } ``` -------------------------------- ### Install TypeChain via npm Source: https://github.com/dethcrypto/typechain/blob/master/README.md Install the core TypeChain package as a development dependency. ```bash npm install --save-dev typechain ``` -------------------------------- ### Configure TypeChain Post-install Hook Source: https://github.com/dethcrypto/typechain/blob/master/README.md Add TypeChain to your package.json's postinstall script to automatically regenerate type bindings when dependencies are installed. Ensure generated files are ignored by git. ```json "postinstall":"typechain" ``` -------------------------------- ### Watch for Code Changes and Recompile Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Starts a watch process to automatically recompile projects as changes are made. Useful during development. ```sh pnpm watch ``` -------------------------------- ### Solidity Function Definition Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-truffle-v5/CHANGELOG.md Example of a standard Solidity function returning a single uint256 value. ```solidity function x() public pure returns (uint256) ``` -------------------------------- ### Run TypeChain as an API Source: https://github.com/dethcrypto/typechain/blob/master/README.md Use TypeChain programmatically to generate TypeScript bindings. This example shows how to find ABI files using glob and process them. For incremental generation, ensure `filesToProcess` and `allFiles` are handled appropriately. ```typescript import { runTypeChain, glob } from 'typechain' async function main() { const cwd = process.cwd() // find all files matching the glob const allFiles = glob(cwd, [`${config.paths.artifacts}/!(build-info)/**/+([a-zA-Z0-9_]).json`]) const result = await runTypeChain({ cwd, filesToProcess: allFiles, allFiles, outDir: 'out directory', target: 'target name', }) } main().catch(console.error) ``` -------------------------------- ### Hardhat Test Example with Ethers.js Source: https://context7.com/dethcrypto/typechain/llms.txt Write type-safe tests in Hardhat using generated types with ethers.js and chai matchers. Ensure contracts are deployed and verified before testing methods. ```typescript import { ethers } from 'hardhat' import { expect } from 'chai' import type { Counter } from '../typechain-types' describe('Counter', () => { let counter: Counter beforeEach(async () => { // Get signers const signers = await ethers.getSigners() // Deploy contract - returns typed instance counter = await ethers.deployContract('Counter') // Verify deployment const initialCount = await counter.getCount() expect(initialCount).to.eq(0) expect(await counter.getAddress()).to.be.properAddress }) describe('count up', () => { it('should count up', async () => { // Method calls are fully typed await counter.countUp() const count = await counter.getCount() expect(count).to.eq(1) }) it('should count up multiple times', async () => { await counter.countUp() await counter.countUp() await counter.countUp() expect(await counter.getCount()).to.eq(3) }) }) describe('count down', () => { it('should fail due to underflow', async () => { // Test for expected revert await expect(counter.countDown()).to.be.revertedWith('Uint256 underflow') }) it('should count down after counting up', async () => { await counter.countUp() await counter.countDown() expect(await counter.getCount()).to.eq(0) }) }) }) ``` -------------------------------- ### Ethers + Hardhat Chai Matchers Test with Typechain Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md An example test suite demonstrating how to use generated TypeScript typings for contracts with ethers and Hardhat Chai Matchers. Ensure your contract typings are correctly imported. ```typescript import { ethers } from "hardhat" import chai from "chai" import { Counter } from '../src/types/Counter' const { expect } = chai describe('Counter', () => { let counter: Counter beforeEach(async () => { // 1 const signers = await ethers.getSigners() // 2 counter = await ethers.deployContract("Counter") // 3 const initialCount = await counter.getCount() expect(initialCount).to.eq(0) }) // 4 describe('count up', async () => { it('should count up', async () => { await counter.countUp() let count = await counter.getCount() expect(count).to.eq(1) }) }) describe('count down', async () => { // 5 - this throw a error with solidity ^0.8.0 it('should fail', async () => { await counter.countDown() }) it('should count down', async () => { await counter.countUp() await counter.countDown() const count = await counter.getCount() expect(count).to.eq(0) }) }) }) ``` -------------------------------- ### Package.json Integration for TypeChain Source: https://context7.com/dethcrypto/typechain/llms.txt Configure TypeChain to run automatically during development workflow using npm scripts and post-install hooks. This ensures type generation on installation and provides dedicated scripts for typechain, build, compile, and test. ```json { "scripts": { "postinstall": "typechain --target ethers-v6 --out-dir ./typechain-types './abis/**/*.json'", "typechain": "typechain --target ethers-v6 --out-dir ./typechain-types './abis/**/*.json'", "build": "npm run typechain && tsc", "compile": "hardhat compile", "test": "hardhat test" }, "devDependencies": { "typechain": "^8.3.2", "@typechain/ethers-v6": "^0.5.0", "@typechain/hardhat": "^9.0.0", "typescript": ">=4.3.0" } } ``` -------------------------------- ### Downgrade npm to Version 6 Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Downgrades the npm version to 6.14.17 to resolve a known issue with starting commands in newer npm versions. ```sh npm install -g npm@6.14.17 ``` -------------------------------- ### Deploy and Connect Contracts with TypeChain Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v6/README.md Demonstrates using generated factory classes to deploy a contract and connect to an existing contract instance using an interface. ```typescript import { Wallet } from 'ethers'; import { DummyTokenFactory } from 'typechain-out-dir/DummyTokenFactory'; import { DummyToken } from 'typechain-out-dir/DummyToken'; import { Erc20TokenFactory } from 'typechain-out-dir/Erc20TokenFactory'; const provider = getYourProvider(...); // use the concrete contract factory if you need to operate on the bytecode (ie. deploy) async function deployTestToken(ownerPK: string): Promise { const owner = new Wallet(ownerPK, provider); return new DummyTokenFactory(owner).deploy(); } // to call existing contracts, a factory for both the concrete contract and for the interface // can be used since the ABI is the same async function getTokenBalance(walletAddress: string, tokenAddress: string): Promise { const token = Erc20TokenFactory.connect(tokenAddress, provider); return token.balanceOf(walletAddress); } ``` -------------------------------- ### Build All Packages Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Builds all packages in the monorepo. This command should be run before local linking. ```sh pnpm build ``` -------------------------------- ### Deploy and Connect Contracts with TypeChain Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/README.md Demonstrates using generated factory classes to deploy a contract and connect to an existing contract instance using a typed interface. ```typescript import { BigNumber } from 'ethers'; import { Wallet } from 'ethers'; import { DummyTokenFactory } from 'typechain-out-dir/DummyTokenFactory'; import { DummyToken } from 'typechain-out-dir/DummyToken'; import { Erc20TokenFactory } from 'typechain-out-dir/Erc20TokenFactory'; const provider = getYourProvider(...); // use the concrete contract factory if you need to operate on the bytecode (ie. deploy) async function deployTestToken(ownerPK: string): Promise { const owner = new Wallet(ownerPK, provider); return new DummyTokenFactory(owner).deploy(); } // to call existing contracts, a factory for both the concrete contract and for the interface // can be used since the ABI is the same async function getTokenBalance(walletAddress: string, tokenAddress: string): Promise { const token = Erc20TokenFactory.connect(tokenAddress, provider); return token.balanceOf(walletAddress); } ``` -------------------------------- ### CLI Usage for Multiple ABI Files Source: https://context7.com/dethcrypto/typechain/llms.txt Generates bindings for multiple ABI files located in a specific node module path, outputting to a custom directory. ```bash typechain --target ethers-v6 --out-dir app/contracts './node_modules/neufund-contracts/build/contracts/*.json' ``` -------------------------------- ### Basic CLI Usage with ethers-v6 Source: https://context7.com/dethcrypto/typechain/llms.txt Generates TypeScript bindings for ethers.js v6 from JSON ABI files in a specified directory. ```bash typechain --target ethers-v6 --out-dir ./typechain-types './abis/**/*.json' ``` -------------------------------- ### Deploy Contracts with Ethers.js v6 Source: https://context7.com/dethcrypto/typechain/llms.txt Use generated factory classes to deploy new contract instances with fully typed constructor arguments. Ensure the provider and wallet are correctly initialized. ```typescript import { ethers, Wallet } from 'ethers' import { DummyToken__factory } from './typechain-types/factories/DummyToken__factory' import type { DummyToken } from './typechain-types/DummyToken' async function deployToken(privateKey: string): Promise { const provider = new ethers.JsonRpcProvider('http://localhost:8545') const wallet = new Wallet(privateKey, provider) // Create factory with signer const factory = new DummyToken__factory(wallet) // Deploy with typed constructor arguments const token = await factory.deploy( 'My Token', // name 'MTK', // symbol ethers.parseEther('1000000') // initialSupply ) // Wait for deployment await token.waitForDeployment() const address = await token.getAddress() console.log(`Token deployed at: ${address}`) return token } // Deploy with custom transaction overrides async function deployWithOverrides(wallet: Wallet) { const factory = new DummyToken__factory(wallet) const token = await factory.deploy( 'My Token', 'MTK', ethers.parseEther('1000000'), { gasLimit: 3000000, maxFeePerGas: ethers.parseUnits('50', 'gwei'), maxPriorityFeePerGas: ethers.parseUnits('2', 'gwei') } ) return token } ``` -------------------------------- ### Configure TypeChain options Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Customize the output directory and target environment within the Hardhat configuration object. ```javascript module.exports = { typechain: { outDir: 'src/types', target: 'ethers-v6', alwaysGenerateOverloads: false, // should overloads with full signatures like deposit(uint256) be generated always, even if there are no overloads? externalArtifacts: ['externalArtifacts/*.json'], // optional array of glob patterns with external artifacts to process (for example external libs from node_modules) dontOverrideCompile: false // defaults to false }, } ``` -------------------------------- ### Configure Hardhat with TypeChain Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Register the TypeChain plugin and required dependencies in the Hardhat configuration file. ```javascript require('@typechain/hardhat') require('@nomicfoundation/hardhat-ethers') require('@nomicfoundation/hardhat-chai-matchers') ``` ```typescript import '@typechain/hardhat' import '@nomicfoundation/hardhat-ethers' import '@nomicfoundation/hardhat-chai-matchers' ``` -------------------------------- ### Fix Code Style and Run Tests Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Runs ESLint, Prettier in fix mode, and all tests. Recommended to run before pushing changes. ```sh pnpm test:fix ``` -------------------------------- ### Link Package Locally Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Links a specific package locally after it has been built. Navigate to the desired package directory before running. ```sh pmpm link ``` -------------------------------- ### Execute Hardhat TypeChain Commands Source: https://context7.com/dethcrypto/typechain/llms.txt Use CLI commands to manage contract compilation and type generation cycles. ```bash # Hardhat commands npx hardhat compile # Compiles contracts and generates types npx hardhat compile --no-typechain # Skip type generation npx hardhat typechain # Force full type regeneration npx hardhat clean # Clean artifacts and generated types ``` -------------------------------- ### Compile Contracts and Generate Typescript Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Use this command to compile your Solidity contracts and generate TypeScript typings. This is essential for using TypeChain. ```bash npx hardhat compile ``` -------------------------------- ### Support for `nodenext` style import paths Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Introduces support for `nodenext` style import paths via the `--node16-modules` CLI flag. This feature was added in version 11.0.0. ```bash typechain --node16-modules "./src/**/*.abi.json" --out-dir src/types ``` -------------------------------- ### Optional `config.inputDir` property and `--input-dir` flag Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Allows control over the directory structure in generated types using the optional `config.inputDir` property or the `--input-dir` flag. If not set, the input directory is inferred as the lowest common path of all ABI files. This was added in version 10.0.0. ```bash # Using the CLI flag typechain --input-dir ./abis --out-dir ./generated-types # Using a typechain config file (e.g., typechain.config.js) # module.exports = { # inputDir: './abis', # outDir: './generated-types' # }; ``` -------------------------------- ### Run TypeChain task Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md Manually trigger the regeneration of all type definitions. ```bash hardhat typechain # always regenerates typings to all files ``` -------------------------------- ### Generate Typings with Custom Glob Source: https://github.com/dethcrypto/typechain/blob/master/README.md Run TypeChain with a specified target and a custom glob pattern to find ABI files. Node_modules are always ignored. ```bash typechain --target=your_target "**/*.abi.json" ``` -------------------------------- ### TypeChain CLI Usage Source: https://github.com/dethcrypto/typechain/blob/master/README.md Command-line interface for TypeChain. Specify the target library and glob pattern for ABI files. Optional flags include --out-dir and --always-generate-overloads. ```bash typechain --target=(ethers-v5|ethers-v6|truffle-v4|truffle-v5|web3-v1|path-to-custom-target) [glob] ``` ```bash typechain --target ethers-v6 --out-dir app/contracts './node_modules/neufund-contracts/build/contracts/*.json' ``` -------------------------------- ### CLI Usage with ethers-v5 and Overloads Source: https://context7.com/dethcrypto/typechain/llms.txt Generates bindings for ethers.js v5, enabling overload generation for function types, from ABI files with a .abi extension. ```bash typechain --target ethers-v5 --out-dir ./types --always-generate-overloads './contracts/*.abi' ``` -------------------------------- ### CLI Usage for Node16/ESM Support Source: https://context7.com/dethcrypto/typechain/llms.txt Generates bindings for ethers.js v6 with Node16 module support, adding .js extensions for ESM imports. ```bash typechain --target ethers-v6 --node16-modules --out-dir ./types './abis/*.json' ``` -------------------------------- ### Enable Debugging for TypeChain Source: https://github.com/dethcrypto/typechain/blob/master/CONTRIBUTING.md Enables debug logging for TypeChain by setting the DEBUG environment variable. Useful for troubleshooting. ```sh DEBUG=typechain typechain ``` -------------------------------- ### Configure Hardhat TypeChain Plugin Source: https://context7.com/dethcrypto/typechain/llms.txt Define TypeChain settings within the hardhat.config.ts file to automate type generation during compilation. ```typescript // hardhat.config.ts import '@typechain/hardhat' import '@nomicfoundation/hardhat-ethers' import '@nomicfoundation/hardhat-chai-matchers' import { HardhatUserConfig } from 'hardhat/types' const config: HardhatUserConfig = { solidity: '0.8.19', typechain: { outDir: 'typechain-types', // Output directory (default: 'typechain-types') target: 'ethers-v6', // Target library (default: 'ethers-v6') alwaysGenerateOverloads: false, // Generate overloaded function types discriminateTypes: false, // Add contractName field externalArtifacts: ['external/*.json'], // Include external ABIs dontOverrideCompile: false, // Don't auto-run on compile tsNocheck: false, // Add @ts-nocheck node16Modules: false // ESM support } } export default config ``` -------------------------------- ### Creating a Custom TypeChain Target Source: https://context7.com/dethcrypto/typechain/llms.txt Extend the TypeChainTarget class to create custom TypeChain targets for any library or language. Implement beforeRun, transformFile, and afterRun methods to define custom generation logic. ```typescript import { TypeChainTarget, Config, FileDescription, Output } from 'typechain' export default class MyCustomTarget extends TypeChainTarget { name = 'my-custom-target' constructor(config: Config) { super(config) } // Called once before processing any files beforeRun(): Output { return { path: `${this.cfg.outDir}/common.ts`, contents: `// Common utilities\nexport type Address = string;\n` } } // Called for each ABI file transformFile(file: FileDescription): Output { const abi = JSON.parse(file.contents) const contractName = file.path.split('/').pop()?.replace('.json', '') || 'Contract' // Generate your custom output const generatedCode = ` // Generated for ${contractName} export interface ${contractName} { address: string; // Add your custom generated code here } ` return { path: `${this.cfg.outDir}/${contractName}.ts`, contents: generatedCode } } // Called once after all files are processed afterRun(): Output { // Generate index/barrel file return { path: `${this.cfg.outDir}/index.ts`, contents: `// Barrel file\nexport * from './common';\n` } } }) ``` -------------------------------- ### Programmatic API for Type Generation Source: https://context7.com/dethcrypto/typechain/llms.txt Uses the `runTypeChain` function programmatically to generate TypeScript bindings from ABI files, supporting glob patterns for file discovery. ```typescript import { runTypeChain, glob } from 'typechain' async function generateTypes() { const cwd = process.cwd() // Find all ABI files using glob patterns const allFiles = glob(cwd, ['./artifacts/!(build-info)/**/+([a-zA-Z0-9_]).json']) const result = await runTypeChain({ cwd, filesToProcess: allFiles, // Files to generate types for (subset for incremental) allFiles, outDir: './typechain-types', target: 'ethers-v6', flags: { alwaysGenerateOverloads: false, discriminateTypes: false, tsNocheck: false, node16Modules: false, environment: undefined // Set to 'hardhat' for Hardhat integration } }) console.log(`Generated ${result.filesGenerated} type files`) } generateTypes().catch(console.error) ``` -------------------------------- ### Implement Typed Event Filtering and Handling Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Demonstrates the usage of typed event filters and event listeners with improved TypeScript support. ```typescript const filter = contract.filters.Transfer() // TypedEventFilter<> const result = await contract.queryFilter(filter) // TypedEvent<> result[0].args.from // type support for named event parameters result[0].args[0] // type support by index contract.on(filter, (from, to, value, event) => { from // string to // string value // BigNumber event // TypedEvent<> }) ``` -------------------------------- ### Interact with Contracts using Ethers.js v6 Source: https://context7.com/dethcrypto/typechain/llms.txt Utilize generated factory classes to connect to contracts, call methods, and query events with full type safety. ```typescript import { ethers } from 'ethers' import { Dai__factory } from './typechain-types/factories/Dai__factory' const RPC_URL = 'https://mainnet.infura.io/v3/YOUR_PROJECT_ID' const DAI_ADDRESS = '0x6B175474E89094C44Da98b954EedeAC495271d0F' async function main() { const provider = new ethers.JsonRpcProvider(RPC_URL) // Connect to existing contract - fully typed! const dai = Dai__factory.connect(DAI_ADDRESS, provider) // Call view methods with type safety const balance = await dai.balanceOf('0x70b144972C5Ef6CB941A5379240B74239c418CD4') console.log(`Balance: ${ethers.formatEther(balance)} DAI`) // Get typed event filters const transferFilter = dai.filters.Transfer() // Query events with typed return values const events = await dai.queryFilter(transferFilter, -1000) for (const event of events) { // event.args is fully typed with src, dst, wad properties console.log(`${event.args.src} -> ${event.args.dst}: ${ethers.formatEther(event.args.wad)} DAI`) } // Static call simulation const result = await dai.balanceOf.staticCall('0x70b144972C5Ef6CB941A5379240B74239c418CD4') // Gas estimation const gasEstimate = await dai.transfer.estimateGas( '0x1234567890123456789012345678901234567890', ethers.parseEther('100') ) console.log(`Estimated gas: ${gasEstimate}`) } main().catch(console.error) ``` -------------------------------- ### Support for Solidity Structs in Typechain Source: https://github.com/dethcrypto/typechain/blob/master/packages/typechain/CHANGELOG.md Illustrates how Typechain now supports Solidity structs, transforming them into TypeScript types. This change improves type safety and code readability for contract interactions. ```typescript // before function deposit(amount: { token: string; value: BigNumberish }): Promise // after export type AmountStruct = { token: string; value: BigNumberish } function deposit(amount: AmountStruct): Promise ``` -------------------------------- ### CLI Usage with Contract Name Discrimination Source: https://context7.com/dethcrypto/typechain/llms.txt Generates bindings for ethers.js v6, including contract name discrimination by adding a 'contractName' field to types. ```bash typechain --target ethers-v6 --discriminate-types --out-dir ./types './abis/*.json' ``` -------------------------------- ### Update Contract Method Return Types Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Illustrates the change from object-based return types to array-based return types for Solidity functions. ```typescript x(overrides?: CallOverrides): Promise<{0: BigNumber}>; ``` ```typescript x(overrides?: CallOverrides): Promise<[BigNumber]>; ``` -------------------------------- ### Perform Incremental Type Generation Source: https://context7.com/dethcrypto/typechain/llms.txt Use runTypeChain with separate file lists to process only changed files, improving build performance. ```typescript import { runTypeChain, glob } from 'typechain' async function incrementalGenerate(changedFiles: string[]) { const cwd = process.cwd() // All ABI files in the project const allFiles = glob(cwd, ['./artifacts/**/*.json']) // Only process changed files for faster builds const filesToProcess = changedFiles.length > 0 ? changedFiles : allFiles const result = await runTypeChain({ cwd, filesToProcess, // Only changed files allFiles, // All files (needed for cross-references) outDir: './typechain-types', target: 'ethers-v6', }) console.log(`Incrementally generated ${result.filesGenerated} files`) return result } // Example: regenerate types for a specific changed contract incrementalGenerate(['./artifacts/contracts/Token.sol/Token.json']) ``` -------------------------------- ### Update Solidity Struct Type Definitions Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Shows the transition from inline object types to exported struct types for Solidity function parameters. ```ts // before function deposit(amount: { token: string; value: BigNumberish }): Promise // after export type AmountStruct = { token: string; value: BigNumberish } function deposit(amount: AmountStruct): Promise ``` -------------------------------- ### CLI Usage to Skip TypeScript Checking Source: https://context7.com/dethcrypto/typechain/llms.txt Generates bindings for ethers.js v6 and prepends '@ts-nocheck' to the generated files to skip TypeScript type checking. ```bash typechain --target ethers-v6 --ts-nocheck --out-dir ./types './abis/*.json' ``` -------------------------------- ### TypeScript Compiler Options for TypeChain Source: https://context7.com/dethcrypto/typechain/llms.txt Configure TypeScript compiler options for TypeChain integration. Ensure 'target' is set to 'ES2020' or higher and 'moduleResolution' to 'node16' for ethers-v6 compatibility. These settings are essential for type safety in dApp development. ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "moduleResolution": "node16", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "declaration": true, "outDir": "./dist" }, "include": [ "./src/**/*", "./test/**/*", "./typechain-types/**/*" ], "exclude": [ "node_modules" ] } ``` -------------------------------- ### Troubleshooting Typechain Compilation Source: https://github.com/dethcrypto/typechain/blob/master/packages/hardhat/README.md When Typechain types interfere with Hardhat's config loading, use this environment variable to bypass TypeScript transpilation during compilation. This allows type generation to complete. ```bash TS_NODE_TRANSPILE_ONLY=1 npx hardhat compile ``` -------------------------------- ### Legacy Generated Method Signature Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-truffle-v5/CHANGELOG.md The previous method signature format returning an array of BigNumber values. ```typescript x(txDetails?: Truffle.TransactionDetails): Promise<[BigNumber]>; ``` -------------------------------- ### Support for inputs wrapped in promise for ethers-v5 Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Adds support for handling inputs that are promises in the ethers-v5 target. This feature was introduced in version 10.1.0. ```typescript import { type } from "@typechain/ethers-v5"; export const contract = { "address": "0x0000000000000000000000000000000000000000", "abi": [ { "inputs": [ { "internalType": "uint256", "name": "_value", "type": "uint256" } ], "name": "setValue", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] }; ``` -------------------------------- ### Updated Generated Method Signature Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-truffle-v5/CHANGELOG.md The current method signature format returning an object with numeric keys, enabling standard object destructuring. ```typescript x(txDetails?: Truffle.TransactionDetails): Promise<{0: BigNumber}>; ``` -------------------------------- ### Remove obsolete peer dependency `@ethersproject/bytes` Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md The `target-ethers-v5` package no longer includes the obsolete peer dependency `@ethersproject/bytes@^5.0.0`. This change was made in version 10.2.1. ```bash # No code snippet available, this is a dependency management change. ``` -------------------------------- ### Use Generated Types with Web3.js v1 Source: https://context7.com/dethcrypto/typechain/llms.txt Interact with Web3.js v1 contracts using TypeChain-generated types for type-safe method calls and event subscriptions. Ensure the ABI, RPC URL, and contract address are correctly configured. ```typescript import Web3 from 'web3' import { Dai } from './typechain-types/web3-v1-contracts/Dai' const abi = require('./abi/dai.json') const RPC_URL = 'wss://mainnet.infura.io/ws/v3/YOUR_PROJECT_ID' const DAI_ADDRESS = '0x6B175474E89094C44Da98b954EedeAC495271d0F' async function main() { const web3 = new Web3(RPC_URL) // Create typed contract instance const dai = new web3.eth.Contract(abi, DAI_ADDRESS) as any as Dai // Call methods with type safety const balance = await dai.methods.balanceOf('0x70b144972C5Ef6CB941A5379240B74239c418CD4').call() console.log(`Balance: ${web3.utils.fromWei(balance)} DAI`) // Subscribe to typed events dai.events.Transfer((error, event) => { if (error) { console.error(error) return } // event.returnValues is typed with src, dst, wad console.log(`${web3.utils.fromWei(event.returnValues.wad)} DAI: ${event.returnValues.src} -> ${event.returnValues.dst}`) }) // Send transaction with typed parameters const accounts = await web3.eth.getAccounts() await dai.methods.transfer( '0x1234567890123456789012345678901234567890', web3.utils.toWei('100', 'ether') ).send({ from: accounts[0] }) } main().catch(console.error) ``` -------------------------------- ### Directory tree in generated types reflects input directory tree Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md The directory structure in generated types now mirrors the input ABI files' directory structure. Only the main contract type is re-exported from each file. This change, introduced in version 10.0.0, helps solve name-clashing problems. ```typescript // Assume input ABIs are in 'src/contracts/token/ERC20.abi.json' and 'src/contracts/governance/Governor.abi.json' // Before 10.0.0, all types might be generated in a flat structure. // After 10.0.0, generated types will be in: // - src/types/contracts/token/ERC20.ts // - src/types/contracts/governance/Governor.ts // The main contract type is re-exported from each file, e.g.: // export type { ERC20 } from "./contracts/token/ERC20"; // export type { Governor } from "./contracts/governance/Governor"; ``` -------------------------------- ### Emit interface with named properties for events Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md For every event, TypeChain now emits an interface with its named properties, improving readability and access to event data. This change was introduced in version 10.0.0. ```typescript // Before export type ApprovalEvent = TypedEvent<[string, string, BigNumber], { owner: string; approved: string; tokenId: BigNumber }> // After export interface ApprovalEventObject { owner: string approved: string tokenId: BigNumber } export type ApprovalEvent = TypedEvent<[string, string, BigNumber], ApprovalEventObject> ``` -------------------------------- ### Use Generated Types with Truffle v5 Source: https://context7.com/dethcrypto/typechain/llms.txt Leverage TypeChain-generated Truffle typings for seamless integration with Truffle's artifact system and test framework. Ensure contracts are deployed and accounts are available. ```typescript // test/metacoin.ts const MetaCoin = artifacts.require('MetaCoin') contract('MetaCoin', (accounts) => { it('should put 10000 MetaCoin in the first account', async () => { // Instance is fully typed const metaCoinInstance = await MetaCoin.deployed() // Method calls are type-checked const balance = await metaCoinInstance.getBalance(accounts[0]) assert.equal(balance.toString(), '10000', "10000 wasn't in the first account") }) it('should call a function that depends on a linked library', async () => { const metaCoinInstance = await MetaCoin.deployed() const metaCoinBalance = (await metaCoinInstance.getBalance(accounts[0])).toNumber() const metaCoinEthBalance = (await metaCoinInstance.getBalanceInEth(accounts[0])).toNumber() assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, 'Library function returned unexpected value') }) it('should send coin correctly', async () => { const metaCoinInstance = await MetaCoin.deployed() const accountOne = accounts[0] const accountTwo = accounts[1] const accountOneStartingBalance = (await metaCoinInstance.getBalance(accountOne)).toNumber() const accountTwoStartingBalance = (await metaCoinInstance.getBalance(accountTwo)).toNumber() // Transaction options are typed await metaCoinInstance.sendCoin(accountTwo, 10, { from: accountOne }) const accountOneEndingBalance = (await metaCoinInstance.getBalance(accountOne)).toNumber() const accountTwoEndingBalance = (await metaCoinInstance.getBalance(accountTwo)).toNumber() assert.equal(accountOneEndingBalance, accountOneStartingBalance - 10) assert.equal(accountTwoEndingBalance, accountTwoStartingBalance + 10) }) }) ``` -------------------------------- ### Constant size struct arrays supported Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Ensures proper support for constant-size struct arrays, preventing malformed TypeScript output. This fix was included in version 8.0.4. ```typescript // Example: A struct array of fixed size // struct MyStruct { uint256 value; } // MyStruct[3] fixedArray; // This version ensures that 'fixedArray' is correctly typed in TypeScript. ``` -------------------------------- ### Method overload generation rules Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Defines rules for generating method overloads for `getEvent`, `getFunction`, `decodeFunctionResult`, and `encodeFunctionData`. These rules depend on whether entities are overloaded in the ABI and the `--always-generate-overloads` flag. This was updated in version 10.0.0. ```typescript // Example scenario: // If a function is not overloaded and --always-generate-overloads is off, only the function name is used. // If overloaded, signatures are used for disambiguation. // If --always-generate-overloads is on, additional overloads are generated even for non-ambiguous functions. ``` -------------------------------- ### Prefer `import type` in generated files Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Generated files now prefer `import type` for type-only imports when possible, improving TypeScript's module resolution and type safety. This change was introduced in version 10.0.0. ```typescript // Before version 10.0.0, imports might have been: // import { BigNumber } from "ethers"; // After version 10.0.0, for type-only usage: // import type { BigNumber } from "ethers"; ``` -------------------------------- ### Events with multiple positional parameters fix Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Fixes an issue where events with multiple positional parameters would incorrectly include 'undefined' as an argument in `contract.filters`. This was resolved in version 9.0.0. ```typescript // Before version 9.0.0, an event like: // event Transfer(address indexed from, address indexed to, uint256 value); // might have issues with contract.filters.Transfer.arguments // After version 9.0.0, contract.filters.Transfer.arguments will be correctly populated. ``` -------------------------------- ### Ethers V5 target doesn't emit unused imports Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Optimizes the generated code for the ethers-v5 target by removing unused imports, leading to cleaner output. This change was made in version 8.0.3. ```typescript // Before version 8.0.3, generated files might have included imports that were not used. // After version 8.0.3, these unused imports are removed, resulting in cleaner code. // Example: If 'ethers' was imported but no functions from it were used, the import would be removed. ``` -------------------------------- ### Support for `discriminated unions` to contracts Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Adds support for discriminated unions to contracts generated by TypeChain. This feature was introduced in version 9.0.0. ```typescript // Example: A contract with a state variable that could be one of several types. // TypeChain can now generate types that leverage discriminated unions for better type safety. // interface State { // type: "Loading"; // } | { // type: "Success"; // data: string; // } | { // type: "Error"; // message: string; // } ``` -------------------------------- ### Constant size arrays with length > 4 not emitted as tuples Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Addresses an issue where constant-size arrays with lengths greater than 4 were incorrectly emitted as TypeScript tuples. This was fixed in version 8.0.5. ```typescript // Before version 8.0.5, an array like uint256[5] might have been generated as: // [number, number, number, number, number] // After version 8.0.5, it will be correctly generated as: // number[] or a specific tuple type if applicable and desired. ``` -------------------------------- ### Fix tuples in event signatures and arrays of tuples in functions Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Resolves issues related to tuples in event signatures and arrays of tuples in function parameters. This fix was implemented in version 11.1.0. ```typescript // Before 11.1.0, events or functions with complex tuple structures might have had incorrect type generation. // This version ensures that tuples within event signatures and arrays of tuples in function arguments are handled correctly. ``` -------------------------------- ### Add const assertion for exported ABI Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Introduces a const assertion for exported ABIs to improve type safety. This change is part of version 10.2.0. ```typescript import { type } from "@typechain/ethers-v5"; export const contract = { "address": "0x0000000000000000000000000000000000000000", "abi": [ { "inputs": [ { "internalType": "uint256", "name": "_value", "type": "uint256" } ], "name": "setValue", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] as const }; ``` -------------------------------- ### Structs namespaced using contract name Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Structs are now namespaced using the contract name when available, resolving potential naming conflicts. This major change was introduced in version 9.0.0. ```typescript // Example: If a contract named 'MyToken' has a struct 'TokenInfo' // The generated type would be 'MyToken.TokenInfo' // Before version 9.0.0, it might have been just 'TokenInfo' // After version 9.0.0, it's namespaced to avoid collisions. ``` -------------------------------- ### Fix event name generation for events with arrays Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Corrects the generation of event names when events involve arrays, ensuring accurate type definitions. This fix was implemented in version 9.0.0. ```typescript // Example: An event with an array parameter // event DataStored(uint256[] data); // Previously, the event name generation might have been incorrect. // This version ensures correct naming for such events. ``` -------------------------------- ### Fix type generation for arrays of nested structs Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Addresses an issue with type generation for arrays of nested structs, such as `GovernanceMessage.Call[][] calldata _remoteCalls`. This fix was part of version 10.0.0. ```typescript // Example of a struct with nested arrays interface RemoteCall { target: string; value: BigNumber; } // The generated type would correctly handle arrays of these structs: // governanceMessage.remoteCalls(remoteCallsArray: RemoteCall[][]); ``` -------------------------------- ### Fix for unused type in new ethers-v5 codegen Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Corrects an issue where an unused type was being emitted in the new ethers-v5 code generation. This fix was part of version 10.2.1. ```typescript // This is a code generation fix, no direct code snippet to display. // The generated TypeScript code will be cleaner without the extraneous type. ``` -------------------------------- ### ContractFactory subclasses use explicit 'override' modifiers Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md ContractFactory subclasses now utilize explicit 'override' modifiers, requiring TypeScript version 4.3 or newer. This change was included in version 10.0.0. ```typescript import { ContractFactory, Overrides } from "ethers"; import { Signer } from "@ethersproject/abstract-signer"; interface MyContractFactory extends ContractFactory { // Example of an overridden method deploy(overrides?: Overrides): Promise; } // Example usage: // const factory: MyContractFactory = await ethers.getContractFactory("MyContract"); // const instance = await factory.deploy(); ``` -------------------------------- ### Remove `contractName` fields from contracts and factories Source: https://github.com/dethcrypto/typechain/blob/master/packages/target-ethers-v5/CHANGELOG.md Removes `contractName` fields from contracts and factories to enhance polymorphism, as `contractName` could break type assignability. An optional `--discriminate-types` flag is available to continue emitting `contractName` if needed. This breaking change was introduced in version 10.0.0. ```typescript // Before version 10.0.0, a contract might have had a contractName property: // interface MyContract { // readonly contractName: "MyContract"; // // ... other properties // } // After version 10.0.0, this property is removed by default. // To re-enable it, use the --discriminate-types flag during generation. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.