Defining the State
The attributes of thestruct marked as the contract define the data that will be stored.
The contract can store all native types (e.g. u8, string, HashMap, Vector) as well as complex objects.
For example, our Auction contract stores when the auction ends, and an object representing the highest bid.
The structures that will be saved need a special macro that tells the SDK to store them serialized in Borsh.
The SDK also provides collections to efficiently store collections of data.
lib.rs
Initializing the State
After the contract is deployed, its state is empty and needs to be initialized with some initial values. There are two ways to initialize a state:- By creating an initialization function
- By setting default values
I. Initialization Functions
An option to initialize the state is to create aninitialization function, which needs to be called before executing any other function.
In our Auction example, the contract has an initialization function that sets when the auction ends. The contract derives the PanicOnDefault, which forces the user to call the init method denoted by the #[init] macro.
It is a good practice to mark initialization functions as private. We will cover function types in the functions section.
lib.rs
lib.rs
II. Default State
Another option to initialize the state is to create aDefault version of our contract’s struct.
For example, our “Hello World” contract has a default state with a greeting set to "Hello".
The first time the contract executes, the Default will be stored in the state, and the state will be considered initialized.
The state can only be initialized once.
lib.rs
lib.rs
Lifecycle of the StateWhen a function is called, the contract’s state is loaded from the storage and put into memory.The state is actually stored serialized, and the SDK takes a bit of time to deserialize it before the method can access it.When the method finishes executing successfully, all the changes to the state are serialized, and saved back to the storage.