Solidity Cheats

Immutable String Variables

… use them before the compiler does support them

Mikhail Vladimirov
Published in
2 min readAug 18, 2022

--

This is an article about the Solidity programming language: a special language used to write smart contracts for Ethereum and other compatible blockchains.

Immutable variables are grear. They are virtually as efficient as compile-time constants, however their values could be set at the deployment time.

An important drawback is that currently Solidity supports only immutable variables of primitive types, such as uint or bytes32. Let’s look at the following code from OpenZeppelin:

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L42-L57

The _name and _symbol variables are set in the constructor, and then are never supposed to change, however they are not declared as immutable as the compiler wouldn’t allow this. Thus, these variables are expensive to read and even more expansive to initialize.

Here is a cheat that could help:

This simple library efficiently packs a short string (shorter than 32 bytes) into a bytes32 value that could be storing in an immutable variable. Later the same library could be used to efficiently unpack a packed bytes32 value back into a normal Solidity string.

New to trading? Try crypto trading bots or copy trading

--

--