Core tools and utilities for the web3.js ecosystem, providing foundational layer functionality for blockchain interactions.
npx @tessl/cli install tessl/npm-web3-core@4.7.0Web3 Core provides foundational infrastructure and utilities for the web3.js ecosystem, serving as the internal backbone for blockchain interactions. It offers comprehensive request management, subscription handling, configuration management, and context coordination across all web3.js packages with full TypeScript support.
npm install web3-coreimport {
Web3Context,
Web3RequestManager,
Web3Config,
Web3SubscriptionManager,
Web3BatchRequest
} from "web3-core";For CommonJS:
const {
Web3Context,
Web3RequestManager,
Web3Config,
Web3SubscriptionManager,
Web3BatchRequest
} = require("web3-core");import { Web3Context, Web3RequestManager } from "web3-core";
// Create request manager with HTTP provider
const requestManager = new Web3RequestManager("https://eth-mainnet.g.alchemy.com/v2/your-api-key");
// Create Web3 context with configuration
const web3Context = new Web3Context({
provider: "https://eth-mainnet.g.alchemy.com/v2/your-api-key",
config: {
defaultBlock: "latest",
transactionSendTimeout: 60000,
transactionConfirmationBlocks: 24
}
});
// Send JSON-RPC request
const blockNumber = await requestManager.send({
method: "eth_blockNumber",
params: []
});
// Create batch request for efficiency
const batch = new web3Context.BatchRequest();
batch.add({ method: "eth_blockNumber", params: [] });
batch.add({ method: "eth_gasPrice", params: [] });
const results = await batch.execute();Web3 Core is built around several key architectural components:
Web3Context provides unified state management and component coordinationWeb3RequestManager handles JSON-RPC communication with blockchain providersWeb3Config manages global and per-instance settings with event notificationWeb3SubscriptionManager manages real-time WebSocket subscriptionsWeb3BatchRequest enables efficient grouping of multiple requestsWeb3EventEmitter provides robust event handling across all componentsUnified context system for managing Web3 instances, configurations, and component coordination. Provides plugin support and extensibility.
class Web3Context<API, RegisteredSubs> extends Web3Config {
constructor(providerOrContext?: string | SupportedProviders<API> | Web3ContextInitOptions<API, RegisteredSubs>);
use<T, T2>(ContextRef: Web3ContextConstructor<T, T2>, ...args: [...T2]): T;
registerPlugin(plugin: Web3PluginBase): void;
setProvider(provider?: SupportedProviders<API> | string): boolean;
}JSON-RPC request handling with provider abstraction, middleware support, and automatic provider detection.
class Web3RequestManager<API> extends Web3EventEmitter {
constructor(provider?: SupportedProviders<API> | string, useRpcCallSpecification?: boolean, requestManagerMiddleware?: RequestManagerMiddleware<API>);
send<Method, ResponseType>(request: Web3APIRequest<API, Method>): Promise<ResponseType>;
sendBatch(request: JsonRpcBatchRequest): Promise<JsonRpcBatchResponse<unknown>>;
setProvider(provider?: SupportedProviders<API> | string): boolean;
}Centralized configuration system with event-driven updates and comprehensive blockchain-specific settings.
abstract class Web3Config extends Web3EventEmitter {
constructor(options?: Partial<Web3ConfigOptions>);
setConfig(options: Partial<Web3ConfigOptions>): void;
// Configuration properties
defaultAccount?: HexString;
defaultBlock: BlockNumberOrTag;
transactionSendTimeout: number;
transactionConfirmationBlocks: number;
handleRevert: boolean;
}
interface Web3ConfigOptions {
handleRevert: boolean;
defaultAccount?: HexString;
defaultBlock: BlockNumberOrTag;
transactionSendTimeout: number;
transactionBlockTimeout: number;
transactionConfirmationBlocks: number;
transactionPollingInterval: number;
transactionPollingTimeout: number;
blockHeaderTimeout: number;
maxListenersWarningThreshold: number;
contractDataInputFill: 'data' | 'input' | 'both';
defaultNetworkId?: Numbers;
defaultChain: string;
defaultHardfork: string;
ignoreGasPricing: boolean;
defaultReturnFormat: DataFormat;
}Real-time WebSocket subscription system for blockchain events with automatic reconnection and event handling.
class Web3SubscriptionManager<API, RegisteredSubs> {
constructor(requestManager: Web3RequestManager<API>, registeredSubscriptions: RegisteredSubs, tolerateUnlinkedSubscription?: boolean);
subscribe<T>(name: T, args?: ConstructorParameters<RegisteredSubs[T]>[0], returnFormat?: DataFormat): Promise<InstanceType<RegisteredSubs[T]>>;
unsubscribe(condition?: ShouldUnsubscribeCondition): Promise<string[]>;
supportsSubscriptions(): boolean;
}
abstract class Web3Subscription<EventMap, ArgsType, API> extends Web3EventEmitter {
subscribe(): Promise<string>;
unsubscribe(): Promise<void>;
resubscribe(): Promise<void>;
}Efficient batching system for grouping multiple JSON-RPC requests into single network calls.
class Web3BatchRequest {
constructor(requestManager: Web3RequestManager);
add<ResponseType>(request: JsonRpcOptionalRequest<unknown>): Web3DeferredPromise<ResponseType>;
execute(options?: {timeout?: number}): Promise<JsonRpcBatchResponse<unknown, unknown>>;
}Robust event emission and handling system with type-safe event listeners and Promise-Event hybrids.
class Web3EventEmitter<T extends Web3EventMap> implements Web3Emitter<T> {
on<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;
once<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;
off<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;
emit<K extends Web3EventKey<T>>(eventName: K, params: T[K]): void;
}
class Web3PromiEvent<ResolveType, EventMap> extends Web3EventEmitter<EventMap> implements Promise<ResolveType> {
then<TResult1, TResult2>(onfulfilled?: ((value: ResolveType) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
catch<TResult>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<ResolveType | TResult>;
}Comprehensive provider support with type guards, capability detection, and seamless integration patterns.
function isWeb3Provider<API>(provider: unknown): provider is Web3BaseProvider<API>;
function isMetaMaskProvider<API>(provider: unknown): provider is MetaMaskProvider<API>;
function isEIP1193Provider<API>(provider: unknown): provider is EIP1193Provider<API>;
function isSupportedProvider<API>(provider: unknown): provider is SupportedProviders<API>;
function isSupportSubscriptions<API>(provider: unknown): boolean;Legacy data formatting functions for backward compatibility. These functions are deprecated and should not be used in new code.
// Input formatters (deprecated - use web3-utils format functions instead)
function inputStorageKeysFormatter(keys: Array<string>): Array<string>;
function inputBlockNumberFormatter(blockNumber: Numbers | undefined): string | undefined;
function inputDefaultBlockNumberFormatter(blockNumber: Numbers | undefined, defaultBlock: Numbers): string | undefined;
function inputAddressFormatter(address: string): string;
function txInputOptionsFormatter(options: TransactionInput): Mutable<TransactionOutput>;
function inputCallFormatter(options: TransactionInput, defaultAccount?: string): TransactionOutput;
function inputTransactionFormatter(options: TransactionInput, defaultAccount?: string): TransactionOutput;
function inputSignFormatter(data: string): string;
function inputTopicFormatter(topic: Topic): Topic | null;
function inputLogFormatter(filter: Filter): Filter;
// Output formatters (deprecated - use web3-utils format functions instead)
function outputProofFormatter(proof: Proof): Proof;
function outputBigIntegerFormatter(number: Numbers): number;
function outputTransactionFormatter(tx: TransactionInput): TransactionOutput;
function outputLogFormatter(log: Partial<LogsInput>): LogsOutput;
function outputTransactionReceiptFormatter(receipt: ReceiptInput): ReceiptOutput;
function outputBlockFormatter(block: BlockInput): BlockOutput;
function outputSyncingFormatter(result: SyncInput): SyncOutput;Note: All formatter functions are deprecated. Use format functions from the web3-utils package instead for new development.
type Web3ContextObject<API, RegisteredSubs> = {
config: Web3ConfigOptions;
provider?: SupportedProviders<API> | string;
requestManager: Web3RequestManager<API>;
subscriptionManager?: Web3SubscriptionManager<API, RegisteredSubs>;
registeredSubscriptions?: RegisteredSubs;
providers: typeof Web3RequestManager.providers;
accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
};
type Web3ContextInitOptions<API, RegisteredSubs> = {
provider?: SupportedProviders<API> | string;
config?: Partial<Web3ConfigOptions>;
registeredSubscriptions?: RegisteredSubs;
accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
};type Web3EventMap = Record<string, unknown>;
type Web3EventKey<T extends Web3EventMap> = string & keyof T;
type Web3EventCallback<T> = (params: T) => void | Promise<void>;
interface Web3Emitter<T extends Web3EventMap> {
on<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;
once<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;
off<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;
emit<K extends Web3EventKey<T>>(eventName: K, params: T[K]): void;
}interface RequestManagerMiddleware<API> {
processRequest<ParamType>(
request: JsonRpcPayload<ParamType>,
options?: {[key: string]: unknown}
): Promise<JsonRpcPayload<ParamType>>;
processResponse<AnotherMethod, ResponseType>(
response: JsonRpcResponse<ResponseType>,
options?: {[key: string]: unknown}
): Promise<JsonRpcResponse<ResponseType>>;
}interface Method {
name: string;
call: string;
}
interface ExtensionObject {
property?: string;
methods: Method[];
}