Contract
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"
});
Type parameters
Name | Type |
---|---|
Abi | extends ContractAbi |
Hierarchy
-
Web3Context
<EthExecutionAPI
, typeofcontractSubscriptions
>↳
Contract
Implements
Web3EventEmitter
<ContractEventEmitterInterface
<Abi
>>
Constructors
constructor
• new Contract<Abi
>(jsonInterface
, context?
, returnFormat?
): Contract
<Abi
>
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
Name | Type |
---|---|
Abi | extends ContractAbi |
Parameters
Name | Type | Description |
---|---|---|
jsonInterface | Abi | The JSON interface for the contract to instantiate. |
context? | Web3Context <unknown , any > | Partial <Web3ContextInitOptions <EthExecutionAPI , { logs : typeof LogsSubscription ; newBlockHeaders : typeof NewHeadsSubscription ; newHeads : typeof NewHeadsSubscription }>> | The context of the contract used for customizing the behavior of the contract. |
returnFormat? | DataFormat | - |
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');
Overrides
Web3Context<EthExecutionAPI, typeof contractSubscriptions>.constructor
Properties
options
• Readonly
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
syncWithContext
• syncWithContext: boolean
= false
Set to true if you want contracts' defaults to sync with global defaults.
Accessors
BatchRequest
• get
BatchRequest(): Object
Will return the Web3BatchRequest constructor.
Returns
Object
Inherited from
Web3Context.BatchRequest
blockHeaderTimeout
• get
blockHeaderTimeout(): number
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
Inherited from
Web3Context.blockHeaderTimeout
• set
blockHeaderTimeout(val
): void
Will set the blockHeaderTimeout
Parameters
Name | Type |
---|---|
val | number |
Returns
void
Inherited from
Web3Context.blockHeaderTimeout
contractDataInputFill
• get
contractDataInputFill(): "input"
| "data"
| "both"
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"
Inherited from
Web3Context.contractDataInputFill
• set
contractDataInputFill(val
): void
Will set the contractDataInputFill
Parameters
Name | Type |
---|---|
val | "input" | "data" | "both" |
Returns
void
Inherited from
Web3Context.contractDataInputFill
currentProvider
• get
currentProvider(): undefined
| Web3BaseProvider
<API
>
Will return the current provider. (The same as provider
)
Returns
undefined
| Web3BaseProvider
<API
>
Returns the current provider
Example
const web3Context = new Web3Context("http://localhost:8545");
console.log(web3Context.provider);
> HttpProvider {
clientUrl: 'http://localhost:8545',
httpProviderOptions: undefined
}
Inherited from
Web3Context.currentProvider
• set
currentProvider(provider
): void
Will set the current provider. (The same as provider
)
Parameters
Name | Type | Description |
---|---|---|
provider | undefined | string | LegacyRequestProvider | LegacySendProvider | LegacySendAsyncProvider | EIP1193Provider <API > | Web3BaseProvider <API > | SimpleProvider <API > | MetaMaskProvider <API > | SupportedProviders The provider to set |
Returns
void
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,
...
}
Inherited from
Web3Context.currentProvider
defaultAccount
• get
defaultAccount(): undefined
| string
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
Inherited from
Web3Context.defaultAccount
• set
defaultAccount(val
): void
Will set the default account.
Parameters
Name | Type |
---|---|
val | undefined | string |
Returns
void
Inherited from
Web3Context.defaultAccount
defaultBlock
• get
defaultBlock(): BlockNumberOrTag
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
Inherited from
Web3Context.defaultBlock
• set
defaultBlock(val
): void
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
Name | Type |
---|---|
val | BlockNumberOrTag |
Returns
void
Inherited from
Web3Context.defaultBlock
defaultCommon
• get
defaultCommon(): undefined
| Common
Will get the default common property The default common property does contain the following Common object:
customChain
-Object
: The custom chain propertiesname
-string
: (optional) The name of the chainnetworkId
-number
: Network ID of the custom chainchainId
-number
: Chain ID of the custom chain
baseChain
-string
: (optional) mainnet, goerli, kovan, rinkeby, or ropstenhardfork
-string
: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london Default isundefined
.
Returns
undefined
| Common
Inherited from
Web3Context.defaultCommon
• set
defaultCommon(val
): void
Will set the default common property
Parameters
Name | Type |
---|---|
val | undefined | Common |
Returns
void
Inherited from
Web3Context.defaultCommon
defaultHardfork
• get
defaultHardfork(): string
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
Inherited from
Web3Context.defaultHardfork
• set
defaultHardfork(val
): void
Will set the default hardfork.
Parameters
Name | Type |
---|---|
val | string |
Returns
void
Inherited from
Web3Context.defaultHardfork
enableExperimentalFeatures
• get
enableExperimentalFeatures(): Object
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
Object
Name | Type |
---|---|
useRpcCallSpecification | boolean |
useSubscriptionWhenCheckingBlockTimeout | boolean |