0
# web3-eth-contract
1
2
web3-eth-contract is a TypeScript library for interacting with Ethereum smart contracts. It provides a type-safe Contract class that enables contract deployment, method calls, event subscriptions, and transaction management with full TypeScript inference from contract ABIs.
3
4
## Package Information
5
6
- **Package Name**: web3-eth-contract
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install web3-eth-contract`
10
11
## Core Imports
12
13
```typescript
14
import { Contract } from "web3-eth-contract";
15
```
16
17
For default import:
18
19
```typescript
20
import Contract from "web3-eth-contract";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const { Contract } = require("web3-eth-contract");
27
// or
28
const Contract = require("web3-eth-contract");
29
```
30
31
## Basic Usage
32
33
```typescript
34
import { Contract } from "web3-eth-contract";
35
36
// Define contract ABI (use 'as const' for type safety)
37
const abi = [
38
{
39
inputs: [{ name: "value", type: "uint256" }],
40
name: "setValue",
41
outputs: [],
42
stateMutability: "nonpayable",
43
type: "function"
44
},
45
{
46
inputs: [],
47
name: "getValue",
48
outputs: [{ name: "", type: "uint256" }],
49
stateMutability: "view",
50
type: "function"
51
}
52
] as const;
53
54
// Create contract instance
55
const contract = new Contract(abi, "0x1234567890123456789012345678901234567890");
56
57
// Call a read-only method
58
const value = await contract.methods.getValue().call();
59
60
// Send a transaction
61
const receipt = await contract.methods.setValue(42).send({
62
from: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef",
63
gas: 100000
64
});
65
66
// Subscribe to events
67
const subscription = await contract.events.ValueChanged();
68
subscription.on('data', (event) => {
69
console.log('Event:', event);
70
});
71
```
72
73
## Architecture
74
75
web3-eth-contract is built around several key components:
76
77
- **Contract Class**: Generic `Contract<Abi>` class providing type-safe contract interactions
78
- **Method Objects**: TypeScript interfaces for contract method calls (`call`, `send`, `estimateGas`)
79
- **Event System**: Contract event subscription and filtering using `ContractLogsSubscription`
80
- **Deployment System**: `DeployerMethodClass` for deploying new contracts
81
- **Type Safety**: Full TypeScript integration with ABI-based type inference
82
- **Web3 Ecosystem**: Integrates with web3-core, web3-eth, web3-types, and other Web3.js packages
83
84
## Capabilities
85
86
### Contract Creation and Management
87
88
Core contract instantiation, configuration management, and Web3 context integration.
89
90
```typescript { .api }
91
class Contract<Abi extends ContractAbi> {
92
constructor(
93
jsonInterface: Abi,
94
address?: Address,
95
options?: ContractInitOptions,
96
context?: Web3ContractContext | Web3Context
97
);
98
99
readonly options: ContractOptions;
100
syncWithContext: boolean;
101
102
// Deployment
103
deploy(deployOptions?: {
104
data?: HexString;
105
input?: HexString;
106
arguments?: ContractConstructorArgs<Abi>;
107
}): DeployerMethodClass<Abi>;
108
109
// Method signature decoding
110
decodeMethodData(data: HexString): DecodedParams & { __method__: string };
111
112
// Contract cloning
113
clone(): Contract<Abi>;
114
}
115
```
116
117
[Contract Management](./contract-management.md)
118
119
### Method Execution
120
121
Contract method calls for both read-only operations and state-changing transactions with full type safety.
122
123
```typescript { .api }
124
interface NonPayableMethodObject<Inputs, Outputs> {
125
call(options?: NonPayableCallOptions): Promise<Outputs>;
126
estimateGas(options?: NonPayableCallOptions): Promise<number>;
127
createAccessList(options?: NonPayableCallOptions): Promise<AccessListResult>;
128
}
129
130
interface PayableMethodObject<Inputs, Outputs> extends NonPayableMethodObject<Inputs, Outputs> {
131
send(options?: PayableCallOptions): Web3PromiEvent<TransactionReceipt, SendTransactionEvents>;
132
}
133
```
134
135
[Method Execution](./method-execution.md)
136
137
### Event Handling
138
139
Event subscription, filtering, and log processing with typed event data based on contract ABI.
140
141
```typescript { .api }
142
interface ContractEventOptions {
143
filter?: Record<string, unknown>;
144
fromBlock?: BlockNumberOrTag;
145
topics?: string[];
146
}
147
148
type ContractBoundEvent = (options?: ContractEventOptions) => ContractLogsSubscription;
149
```
150
151
[Event Handling](./event-handling.md)
152
153
### Contract Deployment
154
155
Deploy new smart contracts with constructor arguments and deployment options.
156
157
```typescript { .api }
158
class DeployerMethodClass<FullContractAbi extends ContractAbi> {
159
deploy(options: {
160
data: Bytes;
161
arguments?: ContractConstructorArgs<FullContractAbi>;
162
}): {
163
send(options?: PayableTxOptions): ContractDeploySend<FullContractAbi>;
164
estimateGas(options?: PayableTxOptions): Promise<number>;
165
createAccessList(options?: PayableTxOptions): Promise<AccessListResult>;
166
};
167
}
168
```
169
170
[Contract Deployment](./contract-deployment.md)
171
172
### Encoding and Utilities
173
174
Low-level encoding, decoding, and utility functions for contract interaction and address generation.
175
176
```typescript { .api }
177
function encodeMethodABI(
178
abi: AbiFunctionFragment,
179
args: unknown[],
180
deployData?: HexString
181
): string;
182
183
function encodeEventABI(
184
abi: AbiEventFragment,
185
options?: ContractEventOptions
186
): { topics: Topic[]; fromBlock?: BlockNumberOrTag };
187
188
function createContractAddress(from: Address, nonce: Numbers): Address;
189
190
function create2ContractAddress(
191
from: Address,
192
salt: Bytes,
193
initCode: Bytes
194
): Address;
195
```
196
197
[Encoding and Utilities](./encoding-utilities.md)
198
199
## Core Types
200
201
```typescript { .api }
202
// Re-exported from web3-types
203
interface ContractOptions {
204
address?: Address;
205
jsonInterface?: ContractAbi;
206
gas?: Numbers;
207
gasPrice?: Numbers;
208
from?: Address;
209
input?: HexString;
210
data?: HexString;
211
}
212
213
interface ContractInitOptions extends ContractOptions {
214
provider?: SupportedProviders;
215
input?: HexString;
216
data?: HexString;
217
}
218
219
// Contract-specific types
220
type Web3ContractContext = Partial<{
221
provider: SupportedProviders;
222
requestManager: Web3RequestManager;
223
config: Web3Configuration;
224
}>;
225
226
interface ContractAbiWithSignature extends ContractAbi {
227
signature?: HexString;
228
}
229
230
// Transaction option types
231
type NonPayableTxOptions = NonPayableCallOptions;
232
type PayableTxOptions = PayableCallOptions;
233
234
// Access list types
235
interface AccessListResult {
236
accessList: AccessList;
237
gasUsed: string;
238
}
239
240
// PromiEvent types
241
type Web3PromiEvent<T, E> = Promise<T> & EventEmitter<E>;
242
243
// Send transaction events
244
interface SendTransactionEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT> {
245
'sending': (payload: any) => void;
246
'sent': (payload: any) => void;
247
'transactionHash': (transactionHash: string) => void;
248
'receipt': (receipt: FormatType<TransactionReceipt, ReturnFormat>) => void;
249
'confirmation': (confirmationNumber: number, receipt: FormatType<TransactionReceipt, ReturnFormat>, latestBlockHash: string) => void;
250
'error': (error: Error, receipt?: FormatType<TransactionReceipt, ReturnFormat>) => void;
251
}
252
253
// Decoded parameters type
254
interface DecodedParams {
255
__length__: number;
256
[key: string]: any;
257
[key: number]: any;
258
}
259
260
// Contract constructor arguments type
261
type ContractConstructorArgs<Abi extends ContractAbi> = Abi extends readonly unknown[]
262
? ContractMethodInputParameters<
263
FilterAbis<Abi, AbiConstructorFragment>['inputs'] extends infer U
264
? U extends readonly unknown[]
265
? U
266
: never
267
: never
268
>
269
: never;
270
```