Storage Patterns¶
Warning
This is example code for learning purposes. Do not use in production without thorough review and testing.
Let’s start with a minimal contract that demonstrates state storage. This contract stores a single integer that can be set by anyone.
Simple Storage¶
1#pragma version >0.3.10
2
3storedData: public(int128)
4
5@deploy
6def __init__(_x: int128):
7 self.storedData = _x
8
9@external
10def set(_x: int128):
11 self.storedData = _x
This example shows:
A public state variable
storedDatawith an auto-generated getterA constructor (
__init__) that sets the initial valueAn external function
set()that modifies state
The public modifier on storedData automatically creates a getter function,
so external contracts can read the value by calling contract.storedData().
Advanced Storage¶
Building on the simple storage example, this contract adds input validation, events, and a reset function.
1#pragma version >0.3.10
2
3event DataChange:
4 setter: indexed(address)
5 value: int128
6
7storedData: public(int128)
8
9@deploy
10def __init__(_x: int128):
11 self.storedData = _x
12
13@external
14def set(_x: int128):
15 assert _x >= 0, "No negative values"
16 assert self.storedData < 100, "Storage is locked when 100 or more is stored"
17 self.storedData = _x
18 log DataChange(setter=msg.sender, value=_x)
19
20@external
21def reset():
22 self.storedData = 0
New concepts introduced:
Events: The
DataChangeevent logs who changed the value and what they changed it to. Theindexedkeyword allows filtering by the setter’s address.Assertions with messages:
assert _x >= 0, "No negative values"reverts with a readable error.Business logic guards: The contract locks when the stored value reaches 100.