11

Can't find any good documentation on creating a raw transaction with contract data in ethers.js. The equivalent in web3 is adding the encodeABI on the data property. Any guidance on this?

This isn't working:

data = myContract.interface.functions.myFunction(value);
const tx = {
   ...
   data
   ...
}

It doesn't seem to recognize this is a function (even though i see the data property there).

eth
  • 85,679
  • 53
  • 285
  • 406
Michael C
  • 453
  • 1
  • 6
  • 14

2 Answers2

8

You can use the populateTransaction mechanism documented here: https://docs.ethers.io/v5/api/contract/contract/

So specifically, that'd be:

const data = await myContract.populateTransaction.myFunction(value);
KevinBrownTech
  • 211
  • 2
  • 6
1

The way you can use populateTransaction in Ether.js is:

const contract = new Contract(CONTRACT_ADDRESS, CONTRACT_ABI, Wallet);
const params = [value];
const action = 'myFunction';
const unsignedTx = await contract.populateTransaction[action](...params);

Then you can simply sign and send your transaction like:

await Wallet.sendTransaction(unsignedTx);
  • 4
    Keep in mind that in v6 (June 2023) the populateTransaction order has been flipped so you need to call it in this order contract[action].populateTransaction(...params); – Nico Serrano Jun 03 '23 at 03:27