1MillionDevs
Published in

1MillionDevs

CompilerError: Stack too deep, try removing local variables. Solved!

Oh no! I got an error! But why?

If you get this error it probably means you have too many function arguments, local variables or return values in your function.

Christian Reitwiessner, creator of Solidity, says this:

There are several situations in which this or similar errors occur. Most are related to too many local variables, parameters or return variables in functions. It might also happen if you have expressions that are too deeply nested.

Don’t worry, if you can’t reduce these things there is a simple solution. Use structs.

A single struct can hold multiple values. Put some of your local variables in a struct and then use the struct.

The implementation of the diamondCut function from the diamond standard used to use this trick.

Instead of declaring 6 local variables it declares a single local variable that is a struct holding the 6 variables. Here’s a snippet:

struct SlotInfo {
uint originalSelectorSlotsLength;
bytes32 selectorSlot;
uint oldSelectorSlotsIndex;
uint oldSelectorSlotIndex;
bytes32 oldSelectorSlot;
bool newSlot;
}
// Using the struct to avoid Stack too deep error
function diamondCut(bytes[] memory _diamondCut) public override {
SlotInfo memory slot;
slot.originalSelectorSlotsLength = $selectorSlotsLength;
... code omitted
if(selectorSlotLength > 0) {
slot.selectorSlot = $selectorSlots[selectorSlotsLength];
}
... code omitted for simplicity

For more ways to avoid the stack too deep error checkout this article: https://soliditydeveloper.com/stacktoodeep

Find a job developing smart contracts using Solidity at delegatecall.careers.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store