0
# Using Generated Types
1
2
This guide shows how to use the TypeScript contract bindings generated by @typechain/ethers-v5 with ethers.js v5.
3
4
## Generated Files Overview
5
6
The target generates several types of files for each contract:
7
8
- **Contract Interface** (`ContractName.ts`): Type-safe contract interface with all methods and events
9
- **Factory Class** (`ContractName__factory.ts`): Factory for deploying or connecting to contracts
10
- **Common Types** (`common.ts`): Shared utility types used across all contracts
11
- **Barrel Exports** (`index.ts`): Convenient re-exports of all generated types
12
13
## Contract Deployment
14
15
### With Constructor Arguments
16
17
```typescript
18
import { ethers } from 'ethers';
19
import { MyToken, MyToken__factory } from './types/ethers-contracts';
20
21
const provider = new ethers.providers.JsonRpcProvider();
22
const signer = provider.getSigner();
23
24
// Deploy with type-safe constructor arguments
25
const factory = new MyToken__factory(signer);
26
const contract: MyToken = await factory.deploy(
27
"My Token", // name parameter
28
"MTK", // symbol parameter
29
18 // decimals parameter
30
);
31
32
await contract.deployed();
33
console.log(`Contract deployed at: ${contract.address}`);
34
```
35
36
### Without Constructor Arguments
37
38
```typescript
39
import { SimpleStorage, SimpleStorage__factory } from './types/ethers-contracts';
40
41
const factory = new SimpleStorage__factory(signer);
42
const contract: SimpleStorage = await factory.deploy();
43
```
44
45
## Connecting to Existing Contracts
46
47
### Using Factory Classes
48
49
```typescript
50
import { MyToken, MyToken__factory } from './types/ethers-contracts';
51
52
const contractAddress = "0x1234...";
53
54
// Connect using factory (recommended)
55
const contract: MyToken = MyToken__factory.connect(contractAddress, signer);
56
57
// Or connect using instance method
58
const factory = new MyToken__factory();
59
const contract2: MyToken = factory.attach(contractAddress).connect(signer);
60
```
61
62
### Using Contract Interface
63
64
```typescript
65
import { ethers } from 'ethers';
66
import { MyToken, MyToken__factory } from './types/ethers-contracts';
67
68
// Create contract instance with interface
69
const contract = new ethers.Contract(
70
contractAddress,
71
MyToken__factory.abi,
72
signer
73
) as MyToken;
74
```
75
76
## Calling Contract Methods
77
78
### View/Pure Functions
79
80
```typescript
81
// Type-safe method calls with return type inference
82
const totalSupply: BigNumber = await contract.totalSupply();
83
const balance: BigNumber = await contract.balanceOf(userAddress);
84
const name: string = await contract.name();
85
86
// Function overloads are supported
87
const allowance1: BigNumber = await contract.allowance(owner, spender);
88
const allowance2: BigNumber = await contract["allowance(address,address)"](owner, spender);
89
```
90
91
### State-Changing Functions
92
93
```typescript
94
// Methods automatically include overrides parameter
95
const tx: ContractTransaction = await contract.transfer(
96
recipientAddress,
97
ethers.utils.parseEther("100")
98
);
99
100
await tx.wait(); // Wait for confirmation
101
102
// With transaction overrides
103
const txWithOverrides: ContractTransaction = await contract.transfer(
104
recipientAddress,
105
ethers.utils.parseEther("100"),
106
{
107
gasLimit: 100000,
108
gasPrice: ethers.utils.parseUnits("20", "gwei")
109
}
110
);
111
```
112
113
### Payable Functions
114
115
```typescript
116
// Payable functions accept PayableOverrides
117
const tx: ContractTransaction = await contract.buyTokens(amount, {
118
value: ethers.utils.parseEther("1.0"), // Send ETH with transaction
119
gasLimit: 200000
120
});
121
```
122
123
## Working with Events
124
125
### Event Filtering
126
127
```typescript
128
// Create type-safe event filters
129
const transferFilter = contract.filters.Transfer(null, userAddress, null);
130
const allTransfersFilter = contract.filters.Transfer();
131
132
// Query past events
133
const events = await contract.queryFilter(transferFilter, -10000); // Last 10k blocks
134
135
// Typed event objects
136
events.forEach(event => {
137
console.log(`Transfer: ${event.args.from} -> ${event.args.to}: ${event.args.value}`);
138
});
139
```
140
141
### Event Listening
142
143
```typescript
144
// Listen for events with type safety
145
contract.on("Transfer", (from: string, to: string, value: BigNumber, event) => {
146
console.log(`Transfer from ${from} to ${to}: ${ethers.utils.formatEther(value)} tokens`);
147
});
148
149
// Listen for specific event instances
150
contract.on(transferFilter, (event) => {
151
// Event is fully typed based on filter
152
console.log("User received tokens:", event.args.value);
153
});
154
```
155
156
## Static Call Methods
157
158
All contract methods are available as static calls for gas estimation and simulation:
159
160
```typescript
161
// Estimate gas for transaction
162
const estimatedGas: BigNumber = await contract.estimateGas.transfer(
163
recipientAddress,
164
ethers.utils.parseEther("100")
165
);
166
167
// Simulate transaction without sending
168
const result = await contract.callStatic.complexCalculation(inputValue);
169
170
// Get populated transaction data
171
const populatedTx = await contract.populateTransaction.transfer(
172
recipientAddress,
173
ethers.utils.parseEther("100")
174
);
175
```
176
177
## Error Handling
178
179
TypeChain generates typed errors for custom contract errors:
180
181
```typescript
182
try {
183
await contract.restrictedFunction();
184
} catch (error) {
185
// Handle specific contract errors
186
if (error.errorName === "Unauthorized") {
187
console.log("User not authorized for this action");
188
}
189
}
190
```
191
192
## Library Contracts and Linking
193
194
For contracts that use external libraries:
195
196
```typescript
197
import { MyLibraryContract__factory } from './types/ethers-contracts';
198
199
// Deploy with library addresses
200
const factory = new MyLibraryContract__factory({
201
"MyLibrary": libraryAddress,
202
"AnotherLibrary": anotherLibraryAddress
203
}, signer);
204
205
const contract = await factory.deploy();
206
```
207
208
## TypeScript Integration
209
210
The generated types work seamlessly with TypeScript:
211
212
```typescript
213
// Inferred return types
214
const balance = await contract.balanceOf(userAddress); // Type: BigNumber
215
const isApproved = await contract.approved(tokenId); // Type: boolean
216
217
// Type-safe function parameters
218
await contract.transfer(
219
"0x1234...", // address
220
ethers.utils.parseEther("100") // uint256
221
);
222
223
// Compile-time error for wrong parameter types
224
await contract.transfer(
225
123, // ❌ Error: Expected string, got number
226
"invalid" // ❌ Error: Expected BigNumberish, got string
227
);
228
```