CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web3

Ethereum JavaScript API for interacting with the Ethereum blockchain with comprehensive TypeScript support, modular architecture, and plugin extensibility.

Pending
Overview
Eval results
Files

smart-contracts.mddocs/

Smart Contract Interaction

The Contract module provides comprehensive functionality for deploying, interacting with, and monitoring Ethereum smart contracts. It offers full TypeScript support with automatic type generation from ABI specifications and handles all aspects of contract lifecycle management.

Capabilities

Contract Constructor

Create contract instances for interaction with deployed contracts or deployment of new contracts.

/**
 * Creates a new contract instance
 * @param jsonInterface - Contract ABI
 * @param address - Contract address (optional for deployment)
 * @param options - Contract options including gas, gasPrice, etc.
 */
class Contract<Abi extends ContractAbi> {
  constructor(jsonInterface: Abi);
  constructor(jsonInterface: Abi, address: Address);
  constructor(jsonInterface: Abi, options: ContractInitOptions);
  constructor(jsonInterface: Abi, address: Address, options: ContractInitOptions);
}

Usage Examples:

// Create contract instance for existing contract
const abi = [...]; // Contract ABI
const contractAddress = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984';
const contract = new web3.eth.Contract(abi, contractAddress);

// Create contract instance for deployment
const contract = new web3.eth.Contract(abi);

// Create with options
const contract = new web3.eth.Contract(abi, contractAddress, {
  from: '0x742C1382...',
  gasPrice: '20000000000'
});

Contract Methods

Execute contract functions with automatic encoding/decoding and full type safety.

interface ContractMethods<Abi extends ContractAbi> {
  [key: string]: ContractMethod<any, any>;
}

interface ContractMethod<Inputs, Outputs> {
  /**
   * Execute a call (read-only) to the contract method
   * @param options - Call options
   * @param blockNumber - Block number for the call
   * @returns Method result
   */
  call(options?: PayableCallOptions, blockNumber?: BlockNumberOrTag): Promise<Outputs>;
  
  /**
   * Send a transaction to execute the contract method
   * @param options - Transaction options
   * @returns PromiEvent with transaction receipt
   */
  send(options: PayableTxOptions): PromiEvent<TransactionReceipt>;
  
  /**
   * Estimate gas required for the method execution
   * @param options - Transaction options
   * @returns Estimated gas amount
   */
  estimateGas(options?: PayableCallOptions): Promise<bigint>;
  
  /**
   * Encode ABI for this method call
   * @param options - Call options
   * @returns Encoded ABI string
   */
  encodeABI(options?: PayableCallOptions): string;
}

Usage Examples:

// Call a read-only method
const totalSupply = await contract.methods.totalSupply().call();
const balance = await contract.methods.balanceOf('0x742C1382...').call();

// Send a transaction
const receipt = await contract.methods.transfer(
  '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
  web3.utils.toWei('10', 'ether')
).send({
  from: '0x742C1382...',
  gas: 100000
});

// Estimate gas
const gasEstimate = await contract.methods.transfer(
  '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
  web3.utils.toWei('10', 'ether')
).estimateGas({ from: '0x742C1382...' });

// Get encoded ABI
const encodedABI = contract.methods.transfer(
  '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
  web3.utils.toWei('10', 'ether')
).encodeABI();

Contract Deployment

Deploy new contracts to the blockchain with constructor parameters and initialization options.

interface ContractDeploySend<Abi extends ContractAbi> {
  /**
   * Send deployment transaction
   * @param options - Deployment options
   * @returns PromiEvent with contract instance
   */
  send(options: PayableTxOptions): PromiEvent<Contract<Abi>>;
  
  /**
   * Estimate gas for deployment
   * @param options - Deployment options
   * @returns Estimated gas amount
   */
  estimateGas(options?: PayableCallOptions): Promise<bigint>;
  
  /**
   * Encode deployment data
   * @returns Encoded deployment data
   */
  encodeABI(): string;
}

/**
 * Deploy a new contract
 * @param options - Deployment options including bytecode and constructor arguments
 * @returns ContractDeploySend instance
 */
deploy(options: ContractDeployOptions): ContractDeploySend<Abi>;

Usage Examples:

// Deploy a new contract
const deployTx = contract.deploy({
  data: '0x608060405234801561001057600080fd5b50...', // Contract bytecode
  arguments: ['TokenName', 'TKN', 18] // Constructor arguments
});

// Send deployment transaction
const newContract = await deployTx.send({
  from: '0x742C1382...',
  gas: 2000000
});

console.log('Contract deployed at:', newContract.options.address);

// Estimate deployment gas
const deployGas = await deployTx.estimateGas({ from: '0x742C1382...' });

Event Handling

Subscribe to contract events and retrieve historical event logs.

interface ContractEvents<Abi extends ContractAbi> {
  [eventName: string]: ContractEvent<any>;
  
  allEvents(options?: EventOptions): EventEmitter;
}

interface ContractEvent<T> {
  /**
   * Subscribe to this event
   * @param options - Event subscription options
   * @returns Event emitter
   */
  (options?: EventOptions): EventEmitter;
  
  /**
   * Get past events for this event type
   * @param options - Event query options
   * @returns Array of event logs
   */
  getPastEvents(options?: EventOptions): Promise<EventLog<T>[]>;
}

/**
 * Get past events for all event types or specific event
 * @param eventName - Event name or 'allEvents'
 * @param options - Event query options
 * @returns Array of event logs
 */
getPastEvents(eventName: string, options?: EventOptions): Promise<EventLog[]>;

Usage Examples:

// Subscribe to Transfer events
contract.events.Transfer({
  filter: { from: '0x742C1382...' }
})
.on('data', (event) => {
  console.log('Transfer event:', event.returnValues);
})
.on('error', console.error);

// Get past Transfer events
const pastEvents = await contract.getPastEvents('Transfer', {
  filter: { from: '0x742C1382...' },
  fromBlock: 0,
  toBlock: 'latest'
});

// Subscribe to all events
contract.events.allEvents()
.on('data', (event) => {
  console.log('Event:', event.event, event.returnValues);
});

Contract Options Management

Manage contract instance configuration and provider settings.

interface ContractOptions {
  address?: Address;
  jsonInterface: ContractAbi;
  data?: string;
  from?: Address;
  gasPrice?: string;
  maxFeePerGas?: string;
  maxPriorityFeePerGas?: string;
  gas?: number;
}

/**
 * Contract options property
 */
options: ContractOptions;

/**
 * Set new provider for the contract
 * @param provider - New provider instance
 */
setProvider(provider: SupportedProviders): void;

/**
 * Get current provider
 */
get currentProvider(): SupportedProviders | undefined;

Usage Examples:

// Access contract options
console.log('Contract address:', contract.options.address);
console.log('Contract ABI:', contract.options.jsonInterface);

// Update contract options
contract.options.from = '0x742C1382...';
contract.options.gas = 200000;

// Change provider
contract.setProvider(new HttpProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'));

Batch Contract Operations

Execute multiple contract calls in a single batch request.

/**
 * Create a batch request for multiple contract operations
 */
class ContractBatch {
  constructor(contract: Contract);
  
  /**
   * Add a method call to the batch
   * @param method - Contract method to call
   * @returns Request object
   */
  add(method: ContractMethod<any, any>): BatchRequest;
  
  /**
   * Execute all batched requests
   * @returns Array of results
   */
  execute(): Promise<any[]>;
}

Types

interface ContractAbi extends ReadonlyArray<AbiFragment> {}

interface AbiFragment {
  type: 'function' | 'constructor' | 'event' | 'fallback' | 'receive';
  name?: string;
  inputs?: AbiInput[];
  outputs?: AbiOutput[];
  stateMutability?: 'pure' | 'view' | 'nonpayable' | 'payable';
  anonymous?: boolean;
}

interface AbiInput {
  name: string;
  type: string;
  indexed?: boolean;
  components?: AbiInput[];
}

interface AbiOutput {
  name: string;
  type: string;
  components?: AbiOutput[];
}

interface ContractInitOptions {
  from?: Address;
  gasPrice?: Numbers;
  maxFeePerGas?: Numbers;
  maxPriorityFeePerGas?: Numbers;
  gas?: Numbers;
  data?: string;
}

interface ContractDeployOptions {
  data: string;
  arguments?: any[];
}

interface EventOptions {
  filter?: Record<string, any>;
  fromBlock?: BlockNumberOrTag;
  toBlock?: BlockNumberOrTag;
  topics?: string[];
}

interface EventLog<T = any> {
  event: string;
  signature: string;
  address: string;
  returnValues: T;
  logIndex: bigint;
  transactionIndex: bigint;
  transactionHash: string;
  blockHash: string;
  blockNumber: bigint;
  raw: {
    data: string;
    topics: string[];
  };
}

interface PayableCallOptions {
  from?: Address;
  gasPrice?: Numbers;
  maxFeePerGas?: Numbers;
  maxPriorityFeePerGas?: Numbers;
  gas?: Numbers;
  value?: Numbers;
}

interface PayableTxOptions extends PayableCallOptions {
  nonce?: Numbers;
  data?: string;
}

Install with Tessl CLI

npx tessl i tessl/npm-web3

docs

account-management.md

core-web3.md

ens.md

ethereum-interaction.md

index.md

providers.md

smart-contracts.md

utilities.md

tile.json