We are learning Cairo
, and writing WTF Cairo Tutorials
for Starknet newbies. The tutorials are based on Cairo 2.2.0
.
Twitter: @0xAA_Science|@WTFAcademy_
WTF Academy Community:Discord|Wechat|Website
All codes and tutorials are open-sourced on GitHub: github.com/WTFAcademy/WTF-Cairo
In this chapter, we will explore constructor
function in Cairo, a special function that initializes the state variables of a contract.
Same as Solidity, the constructor
in Cairo is a special function which will automatically run once during the contract deployment. It is often used to initialize the parameters of a contract, such as setting the owner
address:
#[starknet::contract]
mod owner{
// import contract address related libraries
use starknet::ContractAddress;
use starknet::get_caller_address;
// Define storage variable
#[storage]
struct Storage{
owner: ContractAddress,
}
// Set owner address during deployment
#[constructor]
fn constructor(ref self: ContractState) {
self.owner.write(get_caller_address());
}
}
In the above contract, we've defined a storage variable owner
within the Storage
struct. This owner
is then initialized in the constructor
function to the address of the caller.
- The
constructor
function must be marked with the#[constructor]
attribute. - Each contract can have, at most, one
constructor
.
In this chapter, we introduced the constructor
function in Cairo. This special function will automatically run once during contract deployment, setting the stage for state variables of the contract.