I've been revisiting ethers.js
recently to refresh my understanding of the details and to write a simple tutorial called "WTF Ethers" for beginners.
Twitter: @0xAA_Science
Community: Website wtf.academy | WTF Solidity | discord | WeChat Group Application
All the code and tutorials are open-sourced on GitHub: github.com/WTFAcademy/WTF-Ethers
In this lesson, we will introduce the interface class in ethers.js
and use it to encode calldata.
Interface Class
The interface class in ethers.js
abstracts the ABI encoding and decoding needed for interacting with contracts on the Ethereum network. ABI (Application Binary Interface) is a format similar to API, used to encode various types of data that contracts can process, enabling them to interact. For more information, see WTF Solidity 27: ABI encoding.
We can generate the interface
variable from the abi
, or directly retrieve it from the contract:
The interface class encapsulates several encoding and decoding methods. When interacting with some special contracts (such as proxy contracts), you need to encode parameters and decode return values:
Note: The relevant function must be included in the abi
.
-
getSighash()
: Get the function selector, with the function name or function signature as the parameter. -
encodeDeploy()
: Encode the parameters of the constructor, which can then be appended to the contract bytecode. -
encodeFunctionData()
: Encode the calldata of the function. -
decodeFunctionResult()
: Decode the return value of the function.
Example: Interacting with the WETH
contract on test network
Here, we will use the interface class to encode calldata and repeat the example of interacting with the test network WETH
contract in Lesson 5.
-
Create the
provider
andwallet
variables. -
Create the
WETH
contract instance -
Call the
balanceOf()
function to read theWETH
balance of the wallet address. -
Call the
deposit()
function to convert0.001 ETH
to0.001 WETH
, and print the transaction details and balance. You can see the balance change.

Summary
In this lesson, we introduced the interface classes in ethers.js
and used them to encode calldata
and interact with the WETH
contract. When interacting with specific contracts (such as proxy contracts), you may need to use these methods to encode the parameters and decode the return values.