Ethereum JavaScript API for interacting with the Ethereum blockchain with comprehensive TypeScript support, modular architecture, and plugin extensibility.
npx @tessl/cli install tessl/npm-web3@4.16.0Web3.js is a comprehensive TypeScript library for interacting with the Ethereum blockchain. It provides a complete JavaScript API implementation of Ethereum JSON RPC specifications with modular architecture, tree-shaking support, and plugin extensibility. The library offers abstractions over JSON-RPC calls, dynamic contract type generation, and utilities for account management, transaction handling, smart contract interaction, ENS resolution, and various Ethereum-specific data types and encoding functions.
npm install web3import Web3 from 'web3';For specific modules:
import {
Web3,
Web3Eth,
Contract,
ContractDeploySend,
ContractMethodSend,
Web3Validator,
utils
} from 'web3';For namespace imports:
import { Web3, errors, rpcMethods, validator } from 'web3';CommonJS:
const Web3 = require('web3');import Web3 from 'web3';
// Initialize with provider
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');
// Get account balance
const balance = await web3.eth.getBalance('0x742C1382...1F8E');
console.log(web3.utils.fromWei(balance, 'ether')); // Convert to ether
// Create an account
const account = web3.eth.accounts.create();
console.log(account.address, account.privateKey);
// Interact with a contract
const contract = new web3.eth.Contract(abi, contractAddress);
const result = await contract.methods.someMethod().call();Web3.js is built around several key components:
The main Web3 class that provides access to all Ethereum-related functionality through a unified interface.
class Web3<CustomRegisteredSubscription = RegisteredSubscription> {
constructor(
providerOrContext?:
| string
| SupportedProviders<EthExecutionAPI>
| Web3ContextInitOptions<EthExecutionAPI, CustomRegisteredSubscription>
);
static version: string;
static utils: typeof utils;
static modules: {
Web3Eth: typeof Web3Eth;
Iban: typeof Iban;
Net: typeof Net;
ENS: typeof ENS;
Personal: typeof Personal;
};
}Complete Ethereum blockchain interaction capabilities including account management, transaction handling, and blockchain queries.
interface Web3EthInterface {
// Account management
getBalance(address: Address, blockNumber?: BlockNumberOrTag): Promise<bigint>;
getTransactionCount(address: Address, blockNumber?: BlockNumberOrTag): Promise<bigint>;
// Transaction handling
sendTransaction(transaction: Transaction): PromiEvent<TransactionReceipt>;
estimateGas(transaction: Transaction, blockNumber?: BlockNumberOrTag): Promise<bigint>;
// Contract interaction
Contract: typeof Contract;
// Sub-modules
accounts: AccountsInterface;
abi: AbiInterface;
ens: ENS;
personal: Personal;
net: Net;
}Comprehensive smart contract deployment, interaction, and event handling with full TypeScript support.
class Contract<Abi extends ContractAbi> {
constructor(jsonInterface: Abi, address?: Address, options?: ContractInitOptions);
methods: ContractMethods<Abi>;
events: ContractEvents<Abi>;
deploy(options: ContractDeployOptions): ContractDeploySend<Abi>;
getPastEvents(eventName: string, options?: EventOptions): Promise<EventLog[]>;
}Complete account creation, management, and cryptographic operations including wallet functionality and transaction signing.
interface AccountsInterface {
create(): Web3Account;
privateKeyToAccount(privateKey: Uint8Array | string): Web3Account;
signTransaction(transaction: Transaction, privateKey: Bytes): Promise<SignedTransactionInfoAPI>;
sign(data: string, privateKey: Bytes): SignResult;
recover(signatureObject: SignatureObject): string;
encrypt(privateKey: Bytes, password: string): Promise<KeyStore>;
decrypt(keystore: KeyStore | string, password: string): Promise<Web3Account>;
wallet: Wallet;
privateKeyToAddress(privateKey: Bytes): string;
privateKeyToPublicKey(privateKey: Bytes, isCompressed: boolean): string;
parseAndValidatePrivateKey(data: Bytes, ignoreLength?: boolean): Uint8Array;
}Extensive utility functions for data conversion, validation, hashing, and Ethereum-specific operations.
interface UtilsInterface {
// Data conversion
toWei(value: NumberLike, unit?: EtherUnits): string;
fromWei(value: NumberLike, unit?: EtherUnits): string;
toHex(value: Numbers | Bytes | Address | boolean): HexString;
// Hashing
keccak256(data: Bytes): string;
sha3(data: Bytes): string;
// Validation
isAddress(address: string): boolean;
checkAddressChecksum(address: string): boolean;
// Random
randomHex(bytesSize: number): HexString;
}Flexible provider system supporting multiple connection types with automatic provider detection and EIP-6963 support.
class HttpProvider implements EthExecutionAPI {
constructor(url: string, options?: HttpProviderOptions);
}
class WebSocketProvider implements EthExecutionAPI {
constructor(url: string, clientOptions?: ClientOptions, reconnectOptions?: ReconnectOptions);
}
// EIP-6963 Provider Discovery
function requestEIP6963Providers(): Promise<EIP6963ProviderResponse>;
function onNewProviderDiscovered(callback: (providerEvent: EIP6963ProvidersMapUpdateEvent) => void): void;Complete Ethereum Name Service integration for domain resolution, reverse lookups, and registry interactions.
class ENS {
getAddress(name: string): Promise<string>;
getName(address: string): Promise<string>;
getResolver(name: string): Promise<string>;
getTTL(name: string): Promise<string>;
}Helper types for advanced contract operations and transaction sending.
class ContractDeploySend<Abi extends ContractAbi> {
send(options?: PayableTxOptions): PromiEvent<Contract<Abi>>;
estimateGas(options?: PayableTxOptions): Promise<bigint>;
encodeABI(): string;
}
class ContractMethodSend<Inputs, Outputs> {
send(options?: PayableTxOptions): PromiEvent<TransactionReceipt>;
call(options?: NonPayableTxOptions, block?: BlockNumberOrTag): Promise<Outputs>;
estimateGas(options?: PayableTxOptions): Promise<bigint>;
encodeABI(): string;
}Comprehensive validation utilities for Web3 data types and structures.
class Web3Validator {
static validate(schema: JsonSchema, data: unknown, options?: ValidatorOptions): void;
static validateAndResolve(schema: JsonSchema, data: unknown, options?: ValidatorOptions): any;
}Complete error classes and utilities for Web3 operations (available as errors namespace).
// Error namespace exports
namespace errors {
class Web3Error extends Error;
class ConnectionError extends Web3Error;
class InvalidMethodParamsError extends Web3Error;
class TransactionRevertError extends Web3Error;
// ... and many more error classes
}Low-level RPC method utilities (available as rpcMethods namespace).
// RPC methods namespace exports
namespace rpcMethods {
function ethBlockNumber(): JsonRpcCall;
function ethGetBalance(address: Address, block?: BlockNumberOrTag): JsonRpcCall;
function ethGetTransactionByHash(hash: Bytes): JsonRpcCall;
// ... and many more RPC method builders
}Additional validation utilities (available as validator namespace).
// Validator namespace exports
namespace validator {
function isAddress(value: unknown): boolean;
function isHexStrict(value: unknown): boolean;
function isBloom(value: unknown): boolean;
// ... and many more validation functions
}interface Web3Account {
address: string;
privateKey: string;
signTransaction(transaction: Transaction): Promise<SignedTransactionInfoAPI>;
sign(data: string): SignResult;
encrypt(password: string): Promise<KeyStore>;
}
interface Transaction {
to?: Address;
from?: Address;
value?: Numbers;
gas?: Numbers;
gasPrice?: Numbers;
maxFeePerGas?: Numbers;
maxPriorityFeePerGas?: Numbers;
data?: Bytes;
nonce?: Numbers;
type?: Numbers;
accessList?: AccessList;
}
interface TransactionReceipt {
transactionHash: string;
transactionIndex: bigint;
blockNumber: bigint;
blockHash: string;
from: string;
to: string;
gasUsed: bigint;
cumulativeGasUsed: bigint;
logs: Log[];
status: bigint;
}
type Address = string;
type Bytes = string | Uint8Array;
type Numbers = number | bigint | string;
type HexString = string;