1

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?

Webby
  • 146
  • 10

1 Answers1

2

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),
})
0xSanson
  • 718
  • 1
  • 2
  • 11
  • How do I get contract ABI? How can I import it with `ethers`? – Webby May 09 '22 at 12:45
  • You can import it like any object in javascript. If the contract you want to interact with is verified on etherscan you'll find the ABI under the source code in the same page – 0xSanson May 09 '22 at 15:01
  • do I have to use Etherscan for it? I already use infura API, key now I would have to use also Etherscan API key to get ABI? – Webby May 11 '22 at 13:19
  • It's easier to grab it from website. Example UniswapV2Router https://etherscan.io/address/0x7a250d5630b4cf539739df2c5dacb4c659f2488d#code , you click "Export ABI" > "JSON format" and paste in a file – 0xSanson May 11 '22 at 21:26
  • I need it in the code and also I need it to be simple and dynamic, I cannot just copy paste. Is there another way to import ABI or only by API's? – Webby May 13 '22 at 11:55
  • The ABI you get can be used for all contracts with the same interface. If you are interacting with hundreds of different contracts interfaces then using etherscan API is the quickest. – 0xSanson May 13 '22 at 20:59
  • okay I thought there are other ways of doing it without any API keys etc but I see I have to use it, okay thanks – Webby May 14 '22 at 11:18
  • any idea why this would return `non-payable method cannot override value` – Ciprian Jun 27 '22 at 12:12
  • 1
    @Ciprian right, in this case the function should be marked "payable" in the ABI – 0xSanson Jun 27 '22 at 12:47