Ethers pass method name with parameters instead of hexdata

2.1k views Asked by At

I am using ethers to interact with contracts on Ethereum. This is how my method looks like:

const tx = await signer
      .sendTransaction({
        to: contractAddress,
        value: ethers.utils.parseEther(price),
        data: hex,
        gasPrice: ethers.utils.parseUnits(gas, 9),
      })

And it works fine. But every time I have to look on Etherscan to find transaction hex and pass it to the data parameter. Is it possible to just pass method name from contract and parameters to it instead of passing this hex value?

Maybe there is any method in ethers to encode that method with parameters into hex value?

1

There are 1 answers

9
0xSanson On BEST ANSWER

What you need is the contract ABI. Generally it's written as a json object you can import in your js script, or it can be written like this (human-readable-ABI):

const contractABI = [
  "function foo(uint256 bar) external",
  // other functions or events ...
]

The ABI contains all (or some) methods of a contract and how to encode/decode them.

With the ABI you can create a contract object like this:

const contract = new ethers.Contract(contractAddress, contractABI, provider);

which can be used to send transactions like this:

const my_bar = 123  // example
const tx = await contract.connect(signer).foo(my_bar, {
  value: ethers.utils.parseEther(price),
  gasPrice: ethers.utils.parseUnits(gas, 9),
})