Skip to main content

How to write a constructor

This page explains how to write a constructor function.

To learn more about constructors, read this.

Annotate with #[aztec(private)]

Currently, all constructors in Aztec must be private.

Define your constructor like so:

#[aztec(private)]
fn constructor()

Option 1: Empty constructor

Your constructor does not need to do anything; you can leave it blank like so:

#[aztec(private)]
fn constructor() {}

Option 2: Constructor with logic

Constructors are commonly used to set an admin, such as this example:

constructor
#[aztec(private)]
fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>, decimals: u8) {
let selector = FunctionSelector::from_signature("_initialize((Field),(Field),(Field),u8)");
let name_s = FieldCompressedString::from_string(name);
let symbol_s = FieldCompressedString::from_string(symbol);
context.call_public_function(
context.this_address(),
selector,
[admin.to_field(), name_s.serialize()[0], symbol_s.serialize()[0], decimals as Field]
);
}
Source code: /noir-projects/noir-contracts/contracts/token_contract/src/main.nr#L73-L85 (aztec-packages-v0.24.0)

Here, the constructor is calling a public function. It can also call a private function. Learn more about calling functions from functions here.

To see constructors in action, check out the Aztec.nr getting started guide.