I am writing a Dapp that interacts with a contract that I have deployed. The dapp's frontend needs to read a lot of data at once from the contract. I have experienced an issue where if I move around the site a lot and switch pages I end up calling the contract's getter functions a lot and metamask throws a rate limit error. We decided that to avoid this it would be better to batch all these getters into one getter where it returns a struct of many different variables combined so we only have to read from the contract once or twice on a given page. Is this considered bad practice? Would it be even worse practice to then remove all the individual getters to conserve contract size?
1 Answer
Doing that may look weird from a clean code and design pattern perspective in a traditional code base. But this is smart contract development and sometimes we need to sacrifice good practices in favor of gas saving.
With that said, your approach looks alright for your specific need and scenario.
You also have the option to encode
all that data into bytes
and return that. Then you can decode
it back in when you get it. This is a usual approach in blockchain and smart contract development.
function getDataSummary() public view returns (DataSummary memory) { DataSummary memory summary = DataSummary( val1, val2, val2, val2, val2, val2, val2, val2, val2, val2, val2, val2, val2, val2 ); return summary; }