or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

contract-deployment.mdcontract-management.mdencoding-utilities.mdevent-handling.mdindex.mdmethod-execution.md
tile.json

tessl/npm-web3-eth-contract

Web3 module to interact with Ethereum smart contracts with TypeScript type safety

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

To install, run

npx @tessl/cli install tessl/npm-web3-eth-contract@4.7.0

index.mddocs/

web3-eth-contract

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.

Package Information

  • Package Name: web3-eth-contract
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install web3-eth-contract

Core Imports

import { Contract } from "web3-eth-contract";

For default import:

import Contract from "web3-eth-contract";

For CommonJS:

const { Contract } = require("web3-eth-contract");
// or
const Contract = require("web3-eth-contract");

Basic Usage

import { Contract } from "web3-eth-contract";

// Define contract ABI (use 'as const' for type safety)
const abi = [
  {
    inputs: [{ name: "value", type: "uint256" }],
    name: "setValue",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function"
  },
  {
    inputs: [],
    name: "getValue",
    outputs: [{ name: "", type: "uint256" }],
    stateMutability: "view", 
    type: "function"
  }
] as const;

// Create contract instance
const contract = new Contract(abi, "0x1234567890123456789012345678901234567890");

// Call a read-only method
const value = await contract.methods.getValue().call();

// Send a transaction
const receipt = await contract.methods.setValue(42).send({
  from: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef",
  gas: 100000
});

// Subscribe to events
const subscription = await contract.events.ValueChanged();
subscription.on('data', (event) => {
  console.log('Event:', event);
});

Architecture

web3-eth-contract is built around several key components:

  • Contract Class: Generic Contract<Abi> class providing type-safe contract interactions
  • Method Objects: TypeScript interfaces for contract method calls (call, send, estimateGas)
  • Event System: Contract event subscription and filtering using ContractLogsSubscription
  • Deployment System: DeployerMethodClass for deploying new contracts
  • Type Safety: Full TypeScript integration with ABI-based type inference
  • Web3 Ecosystem: Integrates with web3-core, web3-eth, web3-types, and other Web3.js packages

Capabilities

Contract Creation and Management

Core contract instantiation, configuration management, and Web3 context integration.

class Contract<Abi extends ContractAbi> {
  constructor(
    jsonInterface: Abi,
    address?: Address,
    options?: ContractInitOptions,
    context?: Web3ContractContext | Web3Context
  );
  
  readonly options: ContractOptions;
  syncWithContext: boolean;
  
  // Deployment
  deploy(deployOptions?: {
    data?: HexString;
    input?: HexString;
    arguments?: ContractConstructorArgs<Abi>;
  }): DeployerMethodClass<Abi>;
  
  // Method signature decoding
  decodeMethodData(data: HexString): DecodedParams & { __method__: string };
  
  // Contract cloning
  clone(): Contract<Abi>;
}

Contract Management

Method Execution

Contract method calls for both read-only operations and state-changing transactions with full type safety.

interface NonPayableMethodObject<Inputs, Outputs> {
  call(options?: NonPayableCallOptions): Promise<Outputs>;
  estimateGas(options?: NonPayableCallOptions): Promise<number>;
  createAccessList(options?: NonPayableCallOptions): Promise<AccessListResult>;
}

interface PayableMethodObject<Inputs, Outputs> extends NonPayableMethodObject<Inputs, Outputs> {
  send(options?: PayableCallOptions): Web3PromiEvent<TransactionReceipt, SendTransactionEvents>;
}

Method Execution

Event Handling

Event subscription, filtering, and log processing with typed event data based on contract ABI.

interface ContractEventOptions {
  filter?: Record<string, unknown>;
  fromBlock?: BlockNumberOrTag;
  topics?: string[];
}

type ContractBoundEvent = (options?: ContractEventOptions) => ContractLogsSubscription;

Event Handling

Contract Deployment

Deploy new smart contracts with constructor arguments and deployment options.

class DeployerMethodClass<FullContractAbi extends ContractAbi> {
  deploy(options: {
    data: Bytes;
    arguments?: ContractConstructorArgs<FullContractAbi>;
  }): {
    send(options?: PayableTxOptions): ContractDeploySend<FullContractAbi>;
    estimateGas(options?: PayableTxOptions): Promise<number>;
    createAccessList(options?: PayableTxOptions): Promise<AccessListResult>;
  };
}

Contract Deployment

Encoding and Utilities

Low-level encoding, decoding, and utility functions for contract interaction and address generation.

function encodeMethodABI(
  abi: AbiFunctionFragment,
  args: unknown[],
  deployData?: HexString
): string;

function encodeEventABI(
  abi: AbiEventFragment,
  options?: ContractEventOptions
): { topics: Topic[]; fromBlock?: BlockNumberOrTag };

function createContractAddress(from: Address, nonce: Numbers): Address;

function create2ContractAddress(
  from: Address,
  salt: Bytes,
  initCode: Bytes
): Address;

Encoding and Utilities

Core Types

// Re-exported from web3-types
interface ContractOptions {
  address?: Address;
  jsonInterface?: ContractAbi;
  gas?: Numbers;
  gasPrice?: Numbers;
  from?: Address;
  input?: HexString;
  data?: HexString;
}

interface ContractInitOptions extends ContractOptions {
  provider?: SupportedProviders;
  input?: HexString;
  data?: HexString;
}

// Contract-specific types
type Web3ContractContext = Partial<{
  provider: SupportedProviders;
  requestManager: Web3RequestManager;
  config: Web3Configuration;
}>;

interface ContractAbiWithSignature extends ContractAbi {
  signature?: HexString;
}

// Transaction option types
type NonPayableTxOptions = NonPayableCallOptions;
type PayableTxOptions = PayableCallOptions;

// Access list types
interface AccessListResult {
  accessList: AccessList;
  gasUsed: string;
}

// PromiEvent types
type Web3PromiEvent<T, E> = Promise<T> & EventEmitter<E>;

// Send transaction events
interface SendTransactionEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT> {
  'sending': (payload: any) => void;
  'sent': (payload: any) => void;
  'transactionHash': (transactionHash: string) => void;
  'receipt': (receipt: FormatType<TransactionReceipt, ReturnFormat>) => void;
  'confirmation': (confirmationNumber: number, receipt: FormatType<TransactionReceipt, ReturnFormat>, latestBlockHash: string) => void;
  'error': (error: Error, receipt?: FormatType<TransactionReceipt, ReturnFormat>) => void;
}

// Decoded parameters type
interface DecodedParams {
  __length__: number;
  [key: string]: any;
  [key: number]: any;
}

// Contract constructor arguments type
type ContractConstructorArgs<Abi extends ContractAbi> = Abi extends readonly unknown[]
  ? ContractMethodInputParameters<
      FilterAbis<Abi, AbiConstructorFragment>['inputs'] extends infer U
        ? U extends readonly unknown[]
          ? U
          : never
        : never
    >
  : never;