Search code examples
solidityethers.jshardhat

Create a transaction with data using etherjs


I'm studying the Solidity, and I want to understand how to interact with a smartcotnract and etherjs.

I have a simple function like this:

function buyNumber(uint256 _number) public payable {
      
      
      if(msg.value < 0.1 ether){
        revert("more eth!");
      }

      ...todoStuff

    }

And I have the test

 const tx = {
        from: owner.address,
        to: myContract.address,
        value: ethers.utils.parseEther('0.1'),
        data: '0x4b729aff0000000000000000000000000000000000000000000000000000000000000001'
      }

      let sendTx = await owner.sendTransaction(tx);

      console.log(sendTx)

Now, the transaction works because I get 0x4b729aff0000000000000000000000000000000000000000000000000000000000000001 the function signature and parameters with

 let iface = new ethers.utils.Interface(ABI)
 iface.encodeFunctionData("buyNumber", [ 1 ])
0x4b729aff0000000000000000000000000000000000000000000000000000000000000001

Can I get the same result in easy way? How can I call a function in my contract with params? I could put the msg.value as parameter, but I prefer to use less parameters


Solution

  • You can use the ethers Contract helper class, which allows invoking its methods in a more developer-friedly way, based on the provided contract ABI JSON.

    It does the same thing in the background as your script - encodes the function call to the data value.

    const contract = new ethers.Contract(contractAddress, abiJson, signerInstance);
    
    // the Solidity function accepts 1 param - a number
    // the last param is the `overrides` object - see docs below
    await contract.buyNumber(1, {
        value: ethers.utils.parseEther('0.1')
    });
    

    You can also use the overrides object to specify non-default transaction params. Such as its value (the default value is 0).