or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

batch-processing.mdconfiguration-management.mdcontext-management.mdevent-system.mdindex.mdprovider-integration.mdrequest-management.mdsubscription-management.md
tile.json

tessl/npm-web3-core

Core tools and utilities for the web3.js ecosystem, providing foundational layer functionality for blockchain interactions.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/web3-core@4.7.x

To install, run

npx @tessl/cli install tessl/npm-web3-core@4.7.0

index.mddocs/

Web3 Core

Web3 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.

Package Information

  • Package Name: web3-core
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install web3-core
  • Node.js: >=14
  • Repository: https://github.com/ChainSafe/web3.js

Core Imports

import { 
  Web3Context, 
  Web3RequestManager, 
  Web3Config,
  Web3SubscriptionManager,
  Web3BatchRequest
} from "web3-core";

For CommonJS:

const { 
  Web3Context, 
  Web3RequestManager, 
  Web3Config,
  Web3SubscriptionManager,
  Web3BatchRequest 
} = require("web3-core");

Basic Usage

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();

Architecture

Web3 Core is built around several key architectural components:

  • Context Management: Web3Context provides unified state management and component coordination
  • Request Layer: Web3RequestManager handles JSON-RPC communication with blockchain providers
  • Configuration System: Web3Config manages global and per-instance settings with event notification
  • Subscription Engine: Web3SubscriptionManager manages real-time WebSocket subscriptions
  • Batch Processing: Web3BatchRequest enables efficient grouping of multiple requests
  • Event System: Web3EventEmitter provides robust event handling across all components
  • Type Safety: Comprehensive TypeScript generics preserve type information throughout the stack
  • Provider Abstraction: Support for HTTP, WebSocket, IPC, and custom providers with automatic detection

Capabilities

Context Management

Unified 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;
}

Context Management

Request Management

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;
}

Request Management

Configuration Management

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;
}

Configuration Management

Subscription Management

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>;
}

Subscription Management

Batch Request Processing

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>>;
}

Batch Request Processing

Event System

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>;
}

Event System

Provider Integration

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;

Provider Integration

Deprecated Data Formatters

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.

Types

Core Context Types

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>;
};

Event System Types

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;
}

Middleware Types

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>>;
}

Extension Types

interface Method {
  name: string;
  call: string;
}

interface ExtensionObject {
  property?: string;
  methods: Method[];
}