Cover photo

How to set the gas fee w/thirdweb.js+ethers.js

Introduction

This article is how to set the proper gas fee using thirdweb.js(v3.10.10) and ethers.js(v5.7.2).

Why is this explanation needed?

Because ethers.js has getFeeData() function but it sometimes doesn’t work because the max priority fee is set 1500000000wei, 1.5Gwei.

No kidding.

Don’t use it if you don’t want any bugs.

Hard coding lol.
Hard coding lol.

So I was troubled but finally I got the solution for it.

I’ll share that.

Correct code

This example is to transfer a token of ERC-1155 using thirdweb.js and ethers.js.

In case ERC-721, you can use contract.erc721.transfer instead of contract.erc1155.transfer.

async function transfer(contract, walletAddress, tokenId) {
  const { maxFeePerGas, maxPriorityFeePerGas } = await getFeeData();
  const preTx = await contract.erc1155.transfer.prepare(
    walletAddress,
    tokenId,
    1
  );
  preTx.setMaxFeePerGas(
    ethers.utils.parseUnits(maxFeePerGas.toFixed(9), 'gwei')
  );
  preTx.setMaxPriorityFeePerGas(
    ethers.utils.parseUnits(maxPriorityFeePerGas.toFixed(9), 'gwei')
  );
  await preTx.execute();
}

The perfectly correct getFeeData() function is below.

async function getFeeData(priority = 'standard') {
  const response = await axios.get(
    'https://gasstation.polygon.technology/v2'
  );
  const data = (() => {
    switch (priority) {
      case 'standard':
      default:
        return response.data.standard;
      case 'fast':
        return response.data.fast;
      case 'low':
        return response.data.safeLow;
    }
  })();
  return {
    maxFeePerGas: data.maxFee,
    maxPriorityFeePerGas: data.maxPriorityFee,
  };
}

Conclusion

This bug is terrible but ethers.js is awesome.

thirdweb.js is also awesome.

Bridge to Web3!

https://thirdweb.com/

https://ethers.org/