CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web3-core

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

Pending
Overview
Eval results
Files

context-management.mddocs/

Context Management

The Web3 context system provides unified state management and component coordination for Web3 applications. It serves as the central orchestrator that manages configuration, providers, request managers, subscription managers, and plugins in a cohesive, type-safe environment.

Capabilities

Web3Context Class

The main context class that extends configuration management with provider handling and component orchestration.

/**
 * Main context class providing unified Web3 functionality management
 * @template API - JSON-RPC API specification type
 * @template RegisteredSubs - Registered subscription types
 */
class Web3Context<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends Web3SubscriptionConstructor = Record<string, unknown>> extends Web3Config {
  constructor(providerOrContext?: string | SupportedProviders<API> | Web3ContextInitOptions<API, RegisteredSubs>);
  
  // Component access
  readonly requestManager: Web3RequestManager<API>;
  readonly subscriptionManager?: Web3SubscriptionManager<API, RegisteredSubs>;
  readonly wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
  readonly accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
  readonly provider: Web3BaseProvider<API> | undefined;
  readonly currentProvider: Web3BaseProvider<API> | undefined;
  readonly BatchRequest: new () => Web3BatchRequest;
  
  // Static properties
  static providers: {
    HttpProvider: typeof HttpProvider;
    WebsocketProvider: typeof WebsocketProvider;
  };
  static givenProvider?: SupportedProviders<never>;
  
  // Context management
  use<T, T2 extends unknown[]>(ContextRef: Web3ContextConstructor<T, T2>, ...args: [...T2]): T;
  link<T>(parentContext: T): void;
  
  // Provider management
  setProvider(provider?: SupportedProviders<API> | string): boolean;
  setRequestManagerMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>): void;
  
  // Plugin system  
  registerPlugin(plugin: Web3PluginBase): void;
  
  // Extensibility
  extend(extendObj: ExtensionObject): this;
  
  // Context utilities
  getContextObject(): Web3ContextObject<API, RegisteredSubs>;
  static fromContextObject<T, T3 extends unknown[]>(
    this: Web3ContextConstructor<T, T3>, 
    contextObject: Web3ContextObject, 
    ...args: [...T3]
  ): T;
}

Usage Examples:

import { Web3Context } from "web3-core";
import { EthExecutionAPI } from "web3-types";

// Create context with provider string
const web3 = new Web3Context<EthExecutionAPI>("https://eth-mainnet.g.alchemy.com/v2/your-api-key");

// Create context with configuration
const web3WithConfig = new Web3Context({
  provider: "wss://eth-mainnet.ws.alchemyapi.io/v2/your-api-key",
  config: {
    defaultBlock: "latest",
    transactionSendTimeout: 60000,
    transactionConfirmationBlocks: 24,
    handleRevert: true
  }
});

// Create linked context (shares provider and config)
const linkedContext = web3.use(Web3Context);

// Access components
const requestManager = web3.requestManager;
const subscriptionManager = web3.subscriptionManager;
const batchRequest = new web3.BatchRequest();

Plugin System

Abstract base classes for creating Web3 plugins that extend functionality.

/**
 * Base class for Web3 plugins providing extensibility framework
 * @template API - JSON-RPC API specification type
 */
abstract class Web3PluginBase<API extends Web3APISpec = Web3APISpec> extends Web3Context<API> {
  abstract pluginNamespace: string;
  
  protected registerNewTransactionType<NewTxTypeClass extends new (...args: any[]) => any>(
    type: Numbers, 
    txClass: NewTxTypeClass
  ): void;
}

/**
 * Base class for Ethereum-specific plugins
 * @template API - JSON-RPC API specification type  
 */
abstract class Web3EthPluginBase<API extends Web3APISpec = Web3APISpec> extends Web3PluginBase<API & EthExecutionAPI> {
  // Inherits all Web3PluginBase functionality with Ethereum API types
}

Usage Examples:

import { Web3PluginBase } from "web3-core";

// Create a custom plugin
class MyCustomPlugin extends Web3PluginBase {
  pluginNamespace = "myPlugin";
  
  async getCustomData(address: string) {
    return this.requestManager.send({
      method: "eth_getBalance",
      params: [address, "latest"]
    });
  }
  
  customBatchOperation() {
    const batch = new this.BatchRequest();
    batch.add({ method: "eth_blockNumber", params: [] });
    batch.add({ method: "eth_gasPrice", params: [] });
    return batch.execute();
  }
}

// Register and use plugin
const web3 = new Web3Context("https://eth-mainnet.g.alchemy.com/v2/your-api-key");
const plugin = new MyCustomPlugin();
web3.registerPlugin(plugin);

// Access plugin functionality
const balance = await (web3 as any).myPlugin.getCustomData("0x742d35Cc6634C0532925a3b8D0d3");

Context Initialization Types

Type definitions for configuring Web3 context initialization.

/**
 * Complete context object containing all Web3 components
 * @template API - JSON-RPC API specification type
 * @template RegisteredSubs - Registered subscription types
 */
type Web3ContextObject<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends Web3SubscriptionConstructor = Record<string, unknown>> = {
  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>;
};

/**
 * Options for initializing Web3 context
 * @template API - JSON-RPC API specification type
 * @template RegisteredSubs - Registered subscription types
 */
type Web3ContextInitOptions<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends Web3SubscriptionConstructor = Record<string, unknown>> = {
  provider?: SupportedProviders<API> | string;
  config?: Partial<Web3ConfigOptions>;
  registeredSubscriptions?: RegisteredSubs;
  accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
  wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
};

/**
 * Constructor type for Web3 context classes
 * @template T - Context class type
 * @template T2 - Constructor argument types
 */
type Web3ContextConstructor<T = Web3Context, T2 extends unknown[] = any[]> = {
  new (...args: T2): T;
} & typeof Web3Context;

Extension System

Dynamic extension capabilities for adding custom methods and properties.

/**
 * Method definition for context extensions
 */
interface Method {
  name: string;
  call: string;
}

/**
 * Extension object for adding custom functionality
 */
interface ExtensionObject {
  property?: string;
  methods: Method[];
}

Usage Examples:

// Extend context with custom methods
const web3 = new Web3Context("https://eth-mainnet.g.alchemy.com/v2/your-api-key");

web3.extend({
  property: "customMethods",
  methods: [
    {
      name: "getBlockByHash",
      call: "eth_getBlockByHash"
    },
    {
      name: "getTransactionByHash", 
      call: "eth_getTransactionByHash"
    }
  ]
});

// Access extended methods
const block = await (web3 as any).customMethods.getBlockByHash("0x1234...", true);
const tx = await (web3 as any).customMethods.getTransactionByHash("0x5678...");

Context Sharing and Linking

Mechanisms for sharing context state between multiple Web3 instances.

/**
 * Link context to parent for sharing configuration and providers
 * @template T - Parent context type
 */
link<T>(parentContext: T): void;

/**
 * Create new context instance that shares state with this context
 * @template T - New context type
 * @template T2 - Constructor argument types
 */
use<T, T2 extends unknown[]>(ContextRef: Web3ContextConstructor<T, T2>, ...args: [...T2]): T;

/**
 * Create context from existing context object
 * @template T - Context type
 * @template T3 - Constructor argument types
 */
static fromContextObject<T, T3 extends unknown[]>(
  this: Web3ContextConstructor<T, T3>, 
  contextObject: Web3ContextObject, 
  ...args: [...T3]
): T;

Usage Examples:

// Create parent context
const parentWeb3 = new Web3Context({
  provider: "https://eth-mainnet.g.alchemy.com/v2/your-api-key",
  config: { defaultBlock: "latest" }
});

// Create child context that shares parent's state
const childWeb3 = parentWeb3.use(Web3Context);

// Child inherits parent's provider and config
console.log(childWeb3.provider === parentWeb3.provider); // true
console.log(childWeb3.defaultBlock); // "latest"

// Create context from context object
const contextObj = parentWeb3.getContextObject();
const newWeb3 = Web3Context.fromContextObject(contextObj);

Install with Tessl CLI

npx tessl i tessl/npm-web3-core

docs

batch-processing.md

configuration-management.md

context-management.md

event-system.md

index.md

provider-integration.md

request-management.md

subscription-management.md

tile.json