On Solidity gas optimisation techniques

High gas fees are a problem that Ethereum currently faces. dApp Builders have to be careful so as to optimise their code to cost the least gas to the user. Let's start with a few obvious places to reduce gas: Minimize what you store on-chain. For example if you're building a blog on Ethereum - store the blog in IPFS and the CID in your Solidity. Later on you can optimise this further.

It's often better to compute the value of something off-chain and just enter the value in your code rather recompute it on-chain. This reduces the cost of running functions everytime your code runs. This is where it starts to get non-obvious. When you're coding in something like Python, you'd be OK with calling functions from an another class, but in Solidity, these cost a lot. Store your returned data somewhere and use those.

Simple fetching in Python
Simple fetching in Python

Good place to start from here would be to run eth-gas-reporter on your code to analyse the gas cost of your code to run on the EVM. You'd have a better idea of what's happening now. More often than not, it's a simple fix revolving around how you're storing data or accessing any data.

Storage slot concept: In Solidity, data is stored in "slots" contiguously to make the data storage compact. Since Solidity is statically typed, you'll often use "uint8" or "uint256" or "byte32".

If you keep them unordered, you'd be losing slot space due to tight packing. Keep them ordered in such a way that there is no wastage of storage in slots. (reminder: Ethereum runs on the 256bit/32byte design)

An example
An example

There all nuances to this of course. This packing works for storage, and not for memory or call data. Read up more here. Because of how packing works, uint8 need not always be better than uint256. But you can definitely save up gas by being more specific with you declarations. Avoid using variable-size data types if you can (eg byte32 instead of String).

A niche use-case that some might find useful is using the EIP1167. This reduces redundant on-chain data. I haven't used this myself, but you can read more on this here. And that's all I could remember for this thread. Hope it helped! Will create a check-list for optimisation and share soon if there is any interest in this.

If you enjoyed reading, a retweet/follow sure helps - but it's cool if you don't want to. Happy Diwali if you’re celebrating and have a good day!

Subscribe to August Radjoe (also: abhinavmir)
Receive the latest updates directly to your inbox.
Verification
This entry has been permanently stored onchain and signed by its creator.