Solidity: AppStorage for distinguishing state variables and preventing name clashes

mudgen

Nick Mudge

Posted on January 13, 2022

Solidity: AppStorage for distinguishing state variables and preventing name clashes

Solidity state variables, immutable variables, constants, local variables and function names can look the same and it is possible to have name clashes, where for example a local variable or function name is named the same thing as a state variable, which can reduce code clarity and cause frustration.

AppStorage is a variable naming technique which makes state variables clear in your code and prevents name clashes with other kinds of variables and function names.

This is how it is done: Define a struct in a file and name the struct AppStorage. Define all the state variables in your application within the AppStorage struct.

Then in your smart contracts import the AppStorage struct. Then define this state variable: AppStorage internal s;.

That's it. Now you can access all your state variables by prepending an "s." to them.

Here is a simple example:

  1. Define AppStorage that contains all your state variables:
// AppStorage.sol
struct AppStorage {
  uint256 secondVar;
  uint256 firstVar;
  uint256 lastVar;
  ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Import it and use it in contracts:
import "./AppStorage.sol"

contract Staking {
  AppStorage internal s;

  function myFacetFunction() external {
    s.lastVar = s.firstVar + s.secondVar;
  }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
mudgen
Nick Mudge

Posted on January 13, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024