Skip to main content

Contract <Abi>

The web3.eth.Contract makes it easy to interact with smart contracts on the ethereum blockchain. For using contract package, first install Web3 package using: npm i web3 or yarn add web3 based on your package manager, after that contracts features can be used as mentioned in following snippet.


import { Web3 } from 'web3';

const web3 = new Web3('https://127.0.0.1:4545');
const abi = [...] as const; // your contract ABI

let contract = new web3.eth.Contract(abi,'0xdAC17F958D2ee523a2206206994597C13D831ec7');
await contract.methods.balanceOf('0xdAC17F958D2ee523a2206206994597C13D831ec7').call();

For using individual package install web3-eth-contract and web3-core packages using: npm i web3-eth-contract web3-core or yarn add web3-eth-contract web3-core. This is more efficient approach for building lightweight applications.


import { Web3Context } from 'web3-core';
import { Contract } from 'web3-eth-contract';

const abi = [...] as const; // your contract ABI

let contract = new web3.eth.Contract(
abi,
'0xdAC17F958D2ee523a2206206994597C13D831ec7'
new Web3Context('http://127.0.0.1:8545'));

await contract.methods.balanceOf('0xdAC17F958D2ee523a2206206994597C13D831ec7').call();

Generated Methods

Following methods are generated by web3.js contract object for each of contract functions by using its ABI.

send

This is used to send a transaction to the smart contract and execute its method. Note this can alter the smart contract state.

Parameters

options?: PayableTxOptions | NonPayableTxOptions

Returns

Web3PromiEvent : Web3 Promi Event

// using the promise
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then(function(receipt){
// other parts of code to use receipt
});


// using the event emitter
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.on('transactionHash', function(hash){
// ...
})
.on('confirmation', function(confirmationNumber, receipt){
// ...
})
.on('receipt', function(receipt){
// ...
})
.on('error', function(error, receipt) {
// ...
});

call

This will execute smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state.

Parameters

options?: PayableCallOptions | NonPayableCallOptions, block?: BlockNumberOrTag,

Returns

Promise : having results of call


let myContract = new web3.eth.Contract(abi, address);

myContract.methods.myFunction().call()
.then(console.log);

estimateGas

Returns the amount of gas consumed by executing the method in EVM without creating a new transaction on the blockchain. The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be different when sending the transaction later, as the state of the smart contract can be different at that time.

Parameters

options?: PayableCallOptions, returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,

Returns

Promise: The gas amount estimated.

const estimatedGas = await contract.methods.approve('0xdAC17F958D2ee523a2206206994597C13D831ec7', 300)
.estimateGas();

encodeABI

Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. Set the data field on web3.eth.sendTransaction options as the encodeABI() result and it is the same as calling the contract method with contract.myMethod.send().

Some use cases for encodeABI() include: preparing a smart contract transaction for a multisignature wallet, working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls.

Parameters

None

Returns

String: The encoded ABI.

const encodedABI = await contract.methods.approve('0xdAC17F958D2ee523a2206206994597C13D831ec7', 300)
.encodeABI();

decodeMethodData

Decodes the given ABI-encoded data, revealing both the method name and the parameters used in the smart contract call. This function reverses the encoding process happens at the method encodeABI. It's particularly useful for debugging and understanding the interactions with and between smart contracts.

Parameters

  • data HexString: The string of ABI-encoded data that needs to be decoded. This should include the method signature and the encoded parameters.

Returns

  • Object: This object combines both the decoded parameters and the method name in a readable format. Specifically, the returned object contains:
    • __method__ String: The name of the contract method, reconstructed from the ABI.
    • __length__ Number: The number of parameters decoded.
    • Additional properties representing each parameter by name, as well as their position and values.

Example

Given an ABI-encoded string from a transaction, you can decode this data to identify the method called and the parameters passed. Here's a simplified example:

const GreeterAbi = [
{
inputs: [
{
internalType: 'string',
name: '_greeting',
type: 'string',
},
],
name: 'setGreeting',
outputs: [],
type: 'function',
},
];
const contract = new Contract(GreeterAbi); // Initialize with your contract's ABI

// The ABI-encoded data string for "setGreeting('Hello World')"
const encodedData =
'0xa41368620000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000';

try {
const decoded = contract.decodeMethodData(encodedData);
console.log(decoded.__method__); // Outputs: "setGreeting(string)"
console.log(decoded); // Outputs the detailed parameter data
// This tells that the method called was `setGreeting` with a single string parameter "Hello World":
// {
// __method__: 'setGreeting(string)',
// __length__: 1,
// '0': 'Hello World',
// _greeting: 'Hello World'
// }
} catch (error) {
console.error(error);
}

createAccessList

This will create an access list a method execution will access when executed in the EVM. Note: You must specify a from address and gas if it’s not specified in options when instantiating parent contract object.

Parameters

options?: PayableCallOptions | NonPayableCallOptions, block?: BlockNumberOrTag,

Returns

Promise: The generated access list for transaction.

const accessList = await contract.methods.approve('0xbEe634C21c16F05B03B704BaE071536121e6cFeA', 300)
.createAccessList({
from: "0x9992695e1053bb737d3cfae4743dcfc4b94f203d"
});

Hierarchy

Implements

Index

Constructors

publicconstructor

  • Creates a new contract instance with all its methods and events defined in its ABI provided.

    new web3.eth.Contract(jsonInterface[, address][, options])

    Type parameters

    Parameters

    Returns Contract<Abi>

    • The contract instance with all its methods and events.
    var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
    from: '0x1234567890123456789012345678901234567891', // default from address
    gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
    });

    To use the type safe interface for these contracts you have to include the ABI definitions in your TypeScript project and then declare these as const.

    const myContractAbi = [....] as const; // ABI definitions
    const myContract = new web3.eth.Contract(myContractAbi, '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe');

Properties

config

publicreadonlyoptions

options: ContractOptions

The options object for the contract instance. from, gas and gasPrice are used as fallback values when sending transactions.

myContract.options;
> {
address: '0x1234567890123456789012345678901234567891',
jsonInterface: [...],
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
gasPrice: '10000000000000',
gas: 1000000
}

myContract.options.from = '0x1234567890123456789012345678901234567891'; // default from address
myContract.options.gasPrice = '20000000000000'; // default gas price in wei
myContract.options.gas = 5000000; // provide as fallback always 5M gas

readonlyproviders

providers: { HttpProvider: Web3BaseProviderConstructor; WebsocketProvider: Web3BaseProviderConstructor }

Type declaration

publicsyncWithContext

syncWithContext: boolean = false

Set to true if you want contracts' defaults to sync with global defaults.

staticoptionalgivenProvider

givenProvider?: SupportedProviders<never>

staticreadonlyproviders

providers: { HttpProvider: Web3BaseProviderConstructor; WebsocketProvider: Web3BaseProviderConstructor }

Type declaration

Accessors

BatchRequest

accountProvider

blockHeaderTimeout

  • get blockHeaderTimeout(): number
  • set blockHeaderTimeout(val: number): void
  • The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for 'newBlockHeaders' event before falling back to polling to fetch transaction receipt. Default is 10 seconds.


    Returns number

  • Will set the blockHeaderTimeout


    Parameters

    • val: number

    Returns void

contractDataInputFill

  • get contractDataInputFill(): input | data | both
  • set contractDataInputFill(val: input | data | both): void
  • The contractDataInputFill options property will allow you to set the hash of the method signature and encoded parameters to the property either data, input or both within your contract. This will affect the contracts send, call and estimateGas methods Default is data.


    Returns input | data | both

  • Will set the contractDataInputFill


    Parameters

    • val: input | data | both

    Returns void

currentProvider

  • Will return the current provider. (The same as provider)

    @example
    const web3Context = new Web3Context("http://localhost:8545");
    console.log(web3Context.provider);
    > HttpProvider {
    clientUrl: 'http://localhost:8545',
    httpProviderOptions: undefined
    }

    Returns undefined | Web3BaseProvider<API>

    Returns the current provider

  • Will set the current provider. (The same as provider)

    @example
     const web3Context = new Web3Context("http://localhost:8545");
    web3Context.currentProvider = "ws://localhost:8545";
    console.log(web3Context.provider);
    > WebSocketProvider {
    _eventEmitter: EventEmitter {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    ...
    }

    Parameters

    Returns void

customTransactionSchema

defaultAccount

  • get defaultAccount(): undefined | string
  • set defaultAccount(val: undefined | string): void
  • This default address is used as the default from property, if no from property is specified in for the following methods:

    • web3.eth.sendTransaction()
    • web3.eth.call()
    • myContract.methods.myMethod().call()
    • myContract.methods.myMethod().send()

    Returns undefined | string

  • Will set the default account.


    Parameters

    • val: undefined | string

    Returns void

defaultBlock

  • The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is "latest".

    • web3.eth.getBalance()
    • web3.eth.getCode()
    • web3.eth.getTransactionCount()
    • web3.eth.getStorageAt()
    • web3.eth.call()
    • myContract.methods.myMethod().call()

    Returns BlockNumberOrTag

  • Will set the default block.

    • A block number
    • "earliest" - String: The genesis block
    • "latest" - String: The latest block (current head of the blockchain)
    • "pending" - String: The currently mined block (including pending transactions)
    • "finalized" - String: (For POS networks) The finalized block is one which has been accepted as canonical by greater than 2/3 of validators
    • "safe" - String: (For POS networks) The safe head block is one which under normal network conditions, is expected to be included in the canonical chain. Under normal network conditions the safe head and the actual tip of the chain will be equivalent (with safe head trailing only by a few seconds). Safe heads will be less likely to be reorged than the proof of work network's latest blocks.

    Parameters

    Returns void

defaultChain

  • get defaultChain(): string
  • set defaultChain(val: string): void
  • Returns string

  • Parameters

    • val: string

    Returns void

defaultCommon

  • get defaultCommon(): undefined | Common
  • set defaultCommon(val: undefined | Common): void
  • Will get the default common property The default common property does contain the following Common object:

    • customChain - Object: The custom chain properties
      • name - string: (optional) The name of the chain
      • networkId - number: Network ID of the custom chain
      • chainId - number: Chain ID of the custom chain
    • baseChain - string: (optional) mainnet, goerli, kovan, rinkeby, or ropsten
    • hardfork - string: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london Default is undefined.

    Returns undefined | Common

  • Will set the default common property


    Parameters

    Returns void

defaultHardfork

  • get defaultHardfork(): string
  • set defaultHardfork(val: string): void
  • Will return the default hardfork. Default is london The default hardfork property can be one of the following:

    • chainstart
    • homestead
    • dao
    • tangerineWhistle
    • spuriousDragon
    • byzantium
    • constantinople
    • petersburg
    • istanbul
    • berlin
    • london
    • 'arrowGlacier',
    • 'tangerineWhistle',
    • 'muirGlacier'

    Returns string

  • Will set the default hardfork.


    Parameters

    • val: string

    Returns void

defaultMaxPriorityFeePerGas

  • get defaultMaxPriorityFeePerGas(): Numbers
  • set defaultMaxPriorityFeePerGas(val: Numbers): void
  • Returns Numbers

  • Parameters

    Returns void

defaultNetworkId

  • get defaultNetworkId(): undefined | Numbers
  • set defaultNetworkId(val: undefined | Numbers): void
  • Returns undefined | Numbers

  • Parameters

    Returns void

defaultReturnFormat

  • Returns DataFormat

  • Parameters

    Returns void

defaultTransactionType

  • get defaultTransactionType(): Numbers
  • set defaultTransactionType(val: Numbers): void
  • Returns Numbers

  • Parameters

    Returns void

enableExperimentalFeatures

  • get enableExperimentalFeatures(): { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }
  • set enableExperimentalFeatures(val: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }): void
  • The enableExperimentalFeatures is used to enable trying new experimental features that are still not fully implemented or not fully tested or still have some related issues. Default is false for every feature.


    Returns { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }

    • useRpcCallSpecification: boolean
    • useSubscriptionWhenCheckingBlockTimeout: boolean
  • Will set the enableExperimentalFeatures


    Parameters

    • val: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }
      • useRpcCallSpecification: boolean
      • useSubscriptionWhenCheckingBlockTimeout: boolean

    Returns void

publicevents

  • Subscribe to an event.

    await myContract.events.MyEvent([options])

    There is a special event allEvents that can be used to subscribe all events.

    await myContract.events.allEvents([options])

    Returns ContractEventsInterface<Abi, ContractEvents<Abi>>

    • When individual event is accessed will returns ContractBoundEvent object

givenProvider

  • Will return the givenProvider if available.

    When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise undefined.


    Returns undefined | SupportedProviders<never>

handleRevert

  • get handleRevert(): boolean
  • set handleRevert(val: boolean): void
  • The handleRevert options property returns the revert reason string if enabled for the following methods:

    • web3.eth.sendTransaction()
    • web3.eth.call()
    • myContract.methods.myMethod().call()
    • myContract.methods.myMethod().send() Default is false.

    Note: At the moment handleRevert is only supported for sendTransaction and not for sendSignedTransaction


    Returns boolean

  • Will set the handleRevert


    Parameters

    • val: boolean

    Returns void

ignoreGasPricing

  • get ignoreGasPricing(): boolean
  • set ignoreGasPricing(val: boolean): void
  • Will get the ignoreGasPricing property. When true, the gasPrice, maxPriorityFeePerGas, and maxFeePerGas will not be autofilled in the transaction object. Useful when you want wallets to handle gas pricing.


    Returns boolean

  • Parameters

    • val: boolean

    Returns void

maxListenersWarningThreshold

  • get maxListenersWarningThreshold(): number
  • set maxListenersWarningThreshold(val: number): void
  • Returns number

  • Parameters

    • val: number

    Returns void

publicmethods

  • Creates a transaction object for that method, which then can be called, send, estimated, createAccessList , or ABI encoded.

    The methods of this smart contract are available through:

    The name: myContract.methods.myMethod(123) The name with parameters: myContract.methods['myMethod(uint256)'](123) The signature myContract.methods['0x58cf5f10'](123)

    This allows calling functions with same name but different parameters from the JavaScript contract object.

    &gt; The method signature does not provide a type safe interface, so we recommend to use method name instead.

    // calling a method
    const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});

    // or sending and using a promise
    const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});

    // or sending and using the events
    const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});
    sendObject.on('transactionHash', function(hash){
    ...
    });
    sendObject.on('receipt', function(receipt){
    ...
    });
    sendObject.on('confirmation', function(confirmationNumber, receipt){
    ...
    });
    sendObject.on('error', function(error, receipt) {
    ...
    });

    Returns ContractMethodsInterface<Abi>

    • Either returns PayableMethodObject or NonPayableMethodObject based on the definitions of the ABI of that contract.

provider

  • Will return the current provider.

    @example
    const web3 = new Web3Context("http://localhost:8545");
    console.log(web3.provider);
    > HttpProvider {
    clientUrl: 'http://localhost:8545',
    httpProviderOptions: undefined
    }

    Returns undefined | Web3BaseProvider<API>

    Returns the current provider

  • Will set the current provider.

    @example
     const web3Context = new web3ContextContext("http://localhost:8545");
    web3Context.provider = "ws://localhost:8545";
    console.log(web3Context.provider);
    > WebSocketProvider {
    _eventEmitter: EventEmitter {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    ...
    }

    Parameters

    Returns void

requestManager

publicsubscriptionManager

  • get subscriptionManager(): ContractSubscriptionManager<EthExecutionAPI, any>

transactionBlockTimeout

  • get transactionBlockTimeout(): number
  • set transactionBlockTimeout(val: number): void
  • The transactionBlockTimeout is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. Default is 50.


    Returns number

  • Will set the transactionBlockTimeout.


    Parameters

    • val: number

    Returns void

transactionBuilder

  • Returns undefined | TransactionBuilder<unknown>

  • Parameters

    Returns void

transactionConfirmationBlocks

  • get transactionConfirmationBlocks(): number
  • set transactionConfirmationBlocks(val: number): void
  • This defines the number of blocks it requires until a transaction is considered confirmed. Default is 24.


    Returns number

  • Will set the transactionConfirmationBlocks.


    Parameters

    • val: number

    Returns void

transactionConfirmationPollingInterval

  • get transactionConfirmationPollingInterval(): undefined | number
  • set transactionConfirmationPollingInterval(val: undefined | number): void
  • Returns undefined | number

  • Parameters

    • val: undefined | number

    Returns void

transactionPollingInterval

  • get transactionPollingInterval(): number
  • set transactionPollingInterval(val: number): void
  • Used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. Default is 1000 ms.


    Returns number

  • Will set the transactionPollingInterval.


    Parameters

    • val: number

    Returns void

transactionPollingTimeout

  • get transactionPollingTimeout(): number
  • set transactionPollingTimeout(val: number): void
  • Used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times out, the transaction may still be pending. Default is 750 seconds (12.5 minutes).


    Returns number

  • Will set the transactionPollingTimeout.


    Parameters

    • val: number

    Returns void

transactionReceiptPollingInterval

  • get transactionReceiptPollingInterval(): undefined | number
  • set transactionReceiptPollingInterval(val: undefined | number): void
  • The transactionPollingInterval is used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. Default is undefined


    Returns undefined | number

  • Will set the transactionReceiptPollingInterval


    Parameters

    • val: undefined | number

    Returns void

transactionSendTimeout

  • get transactionSendTimeout(): number
  • set transactionSendTimeout(val: number): void
  • The time used to wait for Ethereum Node to return the sent transaction result. Note: If the RPC call stuck at the Node and therefor timed-out, the transaction may still be pending or even mined by the Network. We recommend checking the pending transactions in such a case. Default is 750 seconds (12.5 minutes).


    Returns number

  • Will set the transactionSendTimeout.


    Parameters

    • val: number

    Returns void

transactionTypeParser

wallet

Methods

publicclone

  • Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone.


    Returns Contract<any>

    • The new contract instance.
    const contract1 = new web3.eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress});

    const contract2 = contract1.clone();
    contract2.options.address = '0xdAC17F958D2ee523a2206206994597C13D831ec7';

    (contract1.options.address !== contract2.options.address);
    > true

publiccontractMethodEstimateGas

  • contractMethodEstimateGas<Options, ReturnFormat>(__namedParameters: { abi: AbiFunctionFragment; contractOptions?: ContractOptions; options?: Options; params: unknown[]; returnFormat: ReturnFormat }): Promise<NumberTypes[ReturnFormat[number]]>

publicdecodeMethodData

  • decodeMethodData(data: string): DecodedParams & { __method__: string }
  • Parameters

    • data: string

    Returns DecodedParams & { __method__: string }

publicdeploy

  • Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance.

    myContract.deploy({
    input: '0x12345...', // data keyword can be used, too.
    arguments: [123, 'My String']
    })
    .send({
    from: '0x1234567890123456789012345678901234567891',
    gas: 1500000,
    gasPrice: '30000000000000'
    }, function(error, transactionHash){ ... })
    .on('error', function(error){ ... })
    .on('transactionHash', function(transactionHash){ ... })
    .on('receipt', function(receipt){
    console.log(receipt.contractAddress) // contains the new contract address
    })
    .on('confirmation', function(confirmationNumber, receipt){ ... })
    .then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
    });


    // When the data is already set as an option to the contract itself
    myContract.options.data = '0x12345...';

    myContract.deploy({
    arguments: [123, 'My String']
    })
    .send({
    from: '0x1234567890123456789012345678901234567891',
    gas: 1500000,
    gasPrice: '30000000000000'
    })
    .then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
    });


    // Simply encoding
    myContract.deploy({
    input: '0x12345...',
    arguments: [123, 'My String']
    })
    .encodeABI();
    > '0x12345...0000012345678765432'


    // decoding
    myContract.deploy({
    input: '0x12345...',
    // arguments: [123, 'My Greeting'] if you just need to decode the data, you can skip the arguments
    })
    .decodeData('0x12345...0000012345678765432');
    > {
    __method__: 'constructor',
    __length__: 2,
    '0': '123',
    _id: '123',
    '1': 'My Greeting',
    _greeting: 'My Greeting',
    }


    // Gas estimation
    myContract.deploy({
    input: '0x12345...',
    arguments: [123, 'My String']
    })
    .estimateGas(function(err, gas){
    console.log(gas);
    });

    Parameters

    • optionaldeployOptions: { arguments?: ContractConstructorArgs<Abi>; data?: string; input?: string }
      • optionalarguments: ContractConstructorArgs<Abi>

        The arguments which get passed to the constructor on deployment.

      • optionaldata: string

        The byte code of the contract.

      • optionalinput: string

    Returns DeployerMethodClass<Abi>

    • The transaction object

emit

  • emit<K>(eventName: K, params: { CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]): void
  • Type parameters

    • K: CONFIG_CHANGE

    Parameters

    • eventName: K
    • params: { CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]

    Returns void

eventNames

  • eventNames(): (string | symbol)[]
  • Returns (string | symbol)[]

extend

  • This method allows extending the web3 modules. Note: This method is only for backward compatibility, and It is recommended to use Web3 v4 Plugin feature for extending web3.js functionality if you are developing something new.


    Parameters

    Returns this

getContextObject

getMaxListeners

  • getMaxListeners(): number
  • Returns number

publicgetPastEvents

  • getPastEvents<ReturnFormat>(returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>
  • getPastEvents<ReturnFormat>(eventName: allEvents | ALLEVENTS | FilterAbis<Abi, AbiBaseFragment & { anonymous?: boolean; inputs?: readonly AbiParameter[]; name: string; type: string } & { type: event }, Abi[number]>[name], returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>
  • getPastEvents<ReturnFormat>(filter: Omit<Filter, address>, returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>
  • getPastEvents<ReturnFormat>(eventName: allEvents | ALLEVENTS | FilterAbis<Abi, AbiBaseFragment & { anonymous?: boolean; inputs?: readonly AbiParameter[]; name: string; type: string } & { type: event }, Abi[number]>[name], filter: Omit<Filter, address>, returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>
  • Gets past events for this contract.

    const events = await myContract.getPastEvents('MyEvent', {
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
    fromBlock: 0,
    toBlock: 'latest'
    });

    > [{
    returnValues: {
    myIndexedParam: 20,
    myOtherIndexedParam: '0x123456789...',
    myNonIndexParam: 'My String'
    },
    raw: {
    data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
    topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
    },
    event: 'MyEvent',
    signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    logIndex: 0,
    transactionIndex: 0,
    transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
    blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    blockNumber: 1234,
    address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
    },{
    ...
    }]

    Type parameters

    • ReturnFormat: DataFormat = { bytes: HEX; number: BIGINT }

    Parameters

    • optionalreturnFormat: ReturnFormat

      Return format

    Returns Promise<(string | EventLog)[]>

    • An array with the past event Objects, matching the given event name and filter.

publicgetTransactionMiddleware

link

  • link<T>(parentContext: T): void
  • Link current context to another context.


    Type parameters

    Parameters

    • parentContext: T

    Returns void

listenerCount

  • listenerCount<K>(eventName: K): number
  • Type parameters

    • K: CONFIG_CHANGE

    Parameters

    • eventName: K

    Returns number

listeners

  • listeners<K>(eventName: K): (...args: any[]) => void[]
  • Type parameters

    • K: CONFIG_CHANGE

    Parameters

    • eventName: K

    Returns (...args: any[]) => void[]

off

  • off<K>(eventName: K, fn: Web3EventCallback<{ CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]>): void
  • Type parameters

    • K: CONFIG_CHANGE

    Parameters

    • eventName: K
    • fn: Web3EventCallback<{ CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]>

    Returns void

on

  • on<K>(eventName: K, fn: Web3EventCallback<{ CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]>): void
  • Type parameters

    • K: CONFIG_CHANGE

    Parameters

    • eventName: K
    • fn: Web3EventCallback<{ CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]>

    Returns void

once

  • once<K>(eventName: K, fn: Web3EventCallback<{ CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]>): void
  • Type parameters

    • K: CONFIG_CHANGE

    Parameters

    • eventName: K
    • fn: Web3EventCallback<{ CONFIG_CHANGE: { name: handleRevert; newValue: boolean; oldValue: boolean } | { name: defaultAccount; newValue: undefined | string; oldValue: undefined | string } | { name: defaultBlock; newValue: BlockNumberOrTag; oldValue: BlockNumberOrTag } | { name: transactionSendTimeout; newValue: number; oldValue: number } | { name: transactionBlockTimeout; newValue: number; oldValue: number } | { name: transactionConfirmationBlocks; newValue: number; oldValue: number } | { name: transactionPollingInterval; newValue: number; oldValue: number } | { name: transactionPollingTimeout; newValue: number; oldValue: number } | { name: transactionReceiptPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: transactionConfirmationPollingInterval; newValue: undefined | number; oldValue: undefined | number } | { name: blockHeaderTimeout; newValue: number; oldValue: number } | { name: maxListenersWarningThreshold; newValue: number; oldValue: number } | { name: contractDataInputFill; newValue: input | data | both; oldValue: input | data | both } | { name: defaultNetworkId; newValue: undefined | Numbers; oldValue: undefined | Numbers } | { name: defaultChain; newValue: string; oldValue: string } | { name: defaultHardfork; newValue: string; oldValue: string } | { name: ignoreGasPricing; newValue: boolean; oldValue: boolean } | { name: defaultCommon; newValue: undefined | Common; oldValue: undefined | Common } | { name: defaultTransactionType; newValue: Numbers; oldValue: Numbers } | { name: defaultMaxPriorityFeePerGas; newValue: Numbers; oldValue: Numbers } | { name: enableExperimentalFeatures; newValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean }; oldValue: { useRpcCallSpecification: boolean; useSubscriptionWhenCheckingBlockTimeout: boolean } } | { name: transactionBuilder; newValue: undefined | TransactionBuilder<unknown>; oldValue: undefined | TransactionBuilder<unknown> } | { name: transactionTypeParser; newValue: undefined | TransactionTypeParser; oldValue: undefined | TransactionTypeParser } | { name: customTransactionSchema; newValue: undefined | CustomTransactionSchema; oldValue: undefined | CustomTransactionSchema } | { name: defaultReturnFormat; newValue: DataFormat; oldValue: DataFormat } }[K]>

    Returns void

registerPlugin

  • Parameters

    Returns void

removeAllListeners

  • Returns EventEmitter

setConfig

  • Parameters

    Returns void

setMaxListenerWarningThreshold

  • setMaxListenerWarningThreshold(maxListenersWarningThreshold: number): void
  • Parameters

    • maxListenersWarningThreshold: number

    Returns void

setProvider

setRequestManagerMiddleware

publicsetTransactionMiddleware

use

  • Use to create new object of any type extended by Web3Context and link it to current context. This can be used to initiate a global context object and then use it to create new objects of any type extended by Web3Context.


    Type parameters

    Parameters

    Returns T

staticfromContextObject