Web3.js Smart Contracts – Combining Multiple Contract Actions into a Single Transaction

contract-invocationgasweb3js

Is it possible to batch multiple smart contract actions / function calls into a single transaction?

For example, I have n NFTs that I would like to call two functions on each. If I interact through Etherscan, I have to pay gas for 2 * n transactions, and would like to avoid this.

  1. Is it possible to batch these together? My current thinking is no, given how the parameters are set up. But maybe (hopefully) I am incorrect and this is possible.

  2. If it possible, do I need to deploy a new smart contract to do that? If I don't need to deploy a smart contract, what would the implementation look like? Do I use something like ethers.js to interact with the contract?

  3. Will batching the actions actually save gas 😂?

Smart Contract:

https://etherscan.io/address/0xc2c747e0f7004f9e8817db2ca4997657a7746928#writeContract

Desired actions:

changeName and transferOwnership for x NFT's

Best Answer

When sending a transaction from an EOA (Externally Owned Account) it always has just one destination with one function call. So you would need to send multiple transactions that way, to interact with multiple contracts.

However, contracts don't have such limitations. A contract can do as much stuff as it wants, as long as the gas limits are respected. So you could create a contract function which does all the work and then you simply need to call that one function.

The tricky part here is that when a contract does things instead of your EOA, the msg.sender is the contract. This means that if you want to do any token transfers and stuff like that, the contract has to own the tokens. So basically you need to delegate your asset ownership to the contract.

Just be careful and remember to implement all required functionality in the contract to handle the assets. If you forget to implement some wanted functionality and you send assets to the contract, you may never be able to get them out of it anymore.

Related Topic