diff --git a/docs/pages/aztec-nr/framework-description/state-variables.md b/docs/pages/aztec-nr/framework-description/state-variables.md index 1b58e47..bebbc6d 100644 --- a/docs/pages/aztec-nr/framework-description/state-variables.md +++ b/docs/pages/aztec-nr/framework-description/state-variables.md @@ -1,12 +1,12 @@ # State Variables -A contract's state is defined by multiple values, e.g. in a token it'd be the total supply, user balances, outstanding approvals, accounts with minting permission, etc. each of these persisting values is called a _state variable_. +A contract's state is defined by multiple values, e.g. in a token it'd be the total supply, user balances, outstanding approvals, accounts with minting permission, etc. Each of these persisting values is called a _state variable_. -One of the first design considerations for any smart contract is how it'll store its state. this is doubly true in aztec due to there being both public and private state - the tradeoff space is large, so there's room for lots of decisions. +One of the first design considerations for any smart contract is how it'll store its state. This is doubly true in Aztec due to there being **both public and private state** - the tradeoff space is large, so there's room for lots of decisions. ## The Storage Struct -State variables are declared in solidity by simply listing them inside of the contract, like so: +State variables are declared in Solidity by simply listing them inside of the contract, like so: ```solidity contract MyContract { @@ -14,9 +14,9 @@ contract MyContract { } ``` -In Aztec.nr we instead define a `struct` (link to noir structs) that holds all state variables. we call this struct **the storage struct**, and it is identified by having the `#[storage]` macro (link to storage api ref) applied to it. +In Aztec.nr, we define a [`struct`](https://noir-lang.org/docs/noir/concepts/data_types/structs) that holds _all_ state variables. This struct is called **the storage struct**, and it is identified by having the `#[storage]` macro applied to it. -```noir +```rust use aztec::macros::aztec; #[aztec] @@ -25,20 +25,21 @@ contract MyContract { #[storage] struct Storage { - // state variables go here + // state variables go here e.g, the admin of the contract + admin: PublicMutable, } } ``` -The storage struct can have any name, but it is typically just called `Storage`. this struct must also have a generic type called C or Context - this is unfortunate boilerplate (link to api ref where we explain _why_ this must exist and what it means - which we don't think is something users need to know about, but some might be curious). +The storage struct can have _any_ name, but it is _typically_ named `Storage`. This struct must also have a generic type called `C` or `Context` - this is an unfortunate boilerplate parameter that provides execution mode information. -> all contract state must be in a single struct. the #[storage] macro can only be used once +The `#[storage]` macro can only be used once so all contract state must be in a **single** struct. ### Accessing Storage -the contract's storage is accessed via `self.storage` in any contract function. it will automatically be tailored to the execution context of that function, hiding all methods that cannot be invoked there. +The contract's storage is accessed via `self.storage` in any contract function. It will automatically be tailored to the execution context of that function, hiding all methods that cannot be invoked there. -consider for example a PublicMutable state variable, which is a value that is fully accessible in public functions, but which cannot be read or written in a private function, and which can only be in utility functions +Consider, for example, a `PublicMutable` state variable, which is a value that is fully accessible in public functions, read-only in utility functions and not accessible in a private function: ```rust #[storage] @@ -65,211 +66,486 @@ fn my_utility_function() { } ``` -### Storage Slots +## Public State Variables -each state variable gets assigned a different*storage slot*, a numerical value. They they are used depends on the kind of state variable: for public state variables they are related to slots in the public data tree, and for private state variables they are metadata that gets included in the note hash. The purpose of slots is the same for both domains however: they keep the values of different state values _separate_ so that they do not interfere with one another. +These are state variables that have _public_ content: everyone on the network can see the values they store. They can be considered to be equivalent to Solidity state variables. -storage slots are a low level detail that users don't typically need to concern themselves with. they are automatically allocated to each state variable by aztecnr and don't require any kind of manual intervention. indeed, utilizing storage slots directly can be dangerous as it may accidentally result in data collisions across state variables, or invariants being broken. +### Choosing a Public State Variable -in some advanced use cases however it can be useful to have access to these low-level details (link to api ref on storage slot stuff), such as when implementing contract upgrades (link to docs) or when interacting with protocol contracts (link). +Public state variables are stored in the network's public storage tree and they can only be written to by public contract functions. It is possible to read _historic_ values of a public state variable in a private contract function, but the current values in the network's public state tree are not accessible in private functions. This means that most public state variables cannot be read from a private function, though there are some exceptions that are documented in the table below. -### The `Packable` trait +Below is a table comparing the key properties of the different public state variables that Aztec.nr offers: -## Public State Variables +| State variable | Mutable? | Readable in private? | Writable in private? | Example use case | +| ---------------------- | ------------------- | -------------------- | -------------------- | ---------------------------------------------------------------------------------- | +| `PublicMutable` | yes | no | no | Configuration of admins, global state (e.g. token total supply, total votes) | +| `PublicImmutable` | no | yes | no | Fixed configuration, one-way actions (e.g. initialization settings for a proposal) | +| `DelayedPublicMutable` | yes (after a delay) | yes | no | Non time sensitive system configuration | -these are state variables that have _public_ content, that is, everyone on the network can see the values they store. they are pretty much equivalent to Solidity state variables. +### PublicMutable -### Choosing a Public State Variable +`PublicMutable` is the simplest kind of public state variable: a value that can be read and written. It is essentially the same as a non-`immutable` or `constant` Solidity state variable. -because they reside in the network's public storage tree (link to foundational concepts), they can only be written to by public contract functions. it is possible to read _past_ values of a public state variable in a private contract function, but the current values of the network's public state tree are not accessible in those. this means that most public state variables cannot be read from a private function - though there's exceptions. +It **cannot be read or written to privately**, but it is possible to call private functions that enqueue a public call in which a `PublicMutable` is accessed. For example, a voting contract may allow private submission of votes which then enqueue a public call in which the vote count, represented as a `PublicMutable`, is incremented. This would let anyone see how many votes have been cast, while preserving the privacy of the account that cast the vote. -below is a table comparing certain key properties of the different public state variables aztec-nr offers. +#### Declaration -| state variable | mutable? | readable in private? | writable in private? | example use case | -| ---------------------- | ------------------- | -------------------- | -------------------- | ---------------------------------------------------------------------------------- | -| `PublicMutable` | yes | no | no | configuration of admins, global state (e.g. token total supply, total votes) | -| `PublicImmutable` | no | yes | no | fixed configuration, one-way actions (e.g. initialization settings for a proposal) | -| `DelayedPublicMutable` | yes (after a delay) | yes | no | non time sensitive system configuration | +Store mutable public state using `PublicMutable` for values that need to be updated throughout the contract's lifecycle. + +```rust +#[storage] +struct Storage { + admin: PublicMutable, + total_supply: PublicMutable, +} +``` + +To add a group of `authorized_users` that are able to perform actions in our contract in public storage: -(make the table have links to sections) +```rust +#[storage] +struct Storage { + authorized_users: Map, Context>, +} +``` + +#### `read` + +`PublicMutable` variables have a `read` method to read the value at the location in storage: + +```rust +#[external("public")] +fn check_admin() { + let admin = self.storage.admin.read(); + assert(admin == self.msg_sender().unwrap(), "caller is not admin"); +} +``` -### Public Mutable (link to apiref) +#### `write` -This is the simplest kind of public state variable: a value that can be read and written. It is essentially the same as a non-`immutable` Solidity state variable. +The `write` method on `PublicMutable` variables takes the value to write as an input and saves this in storage: -It cannot be read or written to privately, but it is possible to call private functions that enqueue a public call (link) in which a `PublicMutable` is accessed. For example, a voting contract may allow private submission of votes which then enqueue a public call in which the vote count, represented as a `PublicMutable`, is incremented. This would let anyone see how many votes have been cast, while preserving the privacy of the account that cast the vote. +```rust +#[external("public")] +fn set_admin(new_admin: AztecAddress) { + self.storage.admin.write(new_admin); +} +``` -### Public Immutable (link to apiref) +### PublicImmutable -This is a simplified version `PublicMutable`: it's a public state variable that can only be written (initialized) once, at which point it can only be read. Unlike Solidity `immutable` state variables, which must be set in the contract's constructor, a `PublicImmutable` can be initialized _at any point in time_ during the contract's lifecycle - attempts to read it prior to initialization will revert. +`PublicImmutable` is a simplified version `PublicMutable`: it's a public state variable that can only be written (initialized) once, at which point it can only be read. Unlike Solidity `immutable` state variables, which must be set in the contract's constructor, a `PublicImmutable` can be initialized _at any point in time_ during the contract's lifecycle and attempts to read it prior to initialization will revert. Due to the value being immutable, it is also possible to read it during private execution - once a circuit proves that the value was set in the past, it knows it cannot have possibly changed. This makes this state variable suitable for immutable public contract configuration or one-off public actions, such as whether a user has signed up or not. -### Delayed Public Mutable (link to apiref) +#### Declaration + +```rust +#[storage] +struct Storage { + contract_version: PublicImmutable, +} +``` + +#### `initialize` + +This function sets the immutable value. It can only be called once. + +```rust +#[external("public")] +fn initialize_version(version: u32) { + self.storage.contract_version.initialize(version); +} +``` + +:::warning +A `PublicImmutable`'s storage **must** only be set once via `initialize`. Attempting to override this by manually accessing the underlying storage slots breaks all properties of the data structure, rendering it useless. +::: + +#### `read` + +Returns the stored immutable value. This function is available in public, private and utility contexts. + +```rust +#[external("public")] +fn get_version() -> u32 { + self.storage.contract_version.read() +} +``` + +### DelayedPublicMutable + +It is sometimes necessary to read public mutable state in private. For example, a decentralized exchange might have a configurable swap fee that some admin sets, but which needs to be read by users in their private swaps. This is where `DelayedPublicMutable` comes in. + +`DelayedPublicMutable` is the same as a `PublicMutable` in that it is a public value that can be read and written, but with a caveat: writes only take effect _after some time delay_. These delays are configurable, but they're typically on the order of a couple hours, if not days, making this state variable unsuitable for actions that must be executed immediately - such as an emergency shut down. It is these very delays that enable private contract functions to _read the current value of a public state variable_, which is otherwise typically impossible. + +The existence of minimum delays means that a private function that reads a public value at an anchor block has a guarantee that said historical value will remain the current value until _at least_ some time in the future - before the delay elapses. As long as the transaction gets included in a block before that time (by using the `include_by_timestamp` tx property), the read value is valid. + +#### Declaration + +Unlike other state variables, `DelayedPublicMutable` receives not only a type parameter for the underlying datatype, but also a `DELAY` type parameter with the value change delay as a number of seconds. + +```rust +global MY_DELAY: u32 = 3600; // 1 hour delay + +#[storage] +struct Storage { + swap_fee: DelayedPublicMutable, +} +``` + +#### `schedule_value_change` + +This is the means by which a `DelayedPublicMutable` variable mutates its contents. It schedules a value change for the variable at a future timestamp after the `DELAY` has elapsed. + +```rust +#[external("public")] +fn set_swap_fee(new_fee: u128) { + assert(self.storage.admin.read() == self.msg_sender().unwrap(), "caller is not admin"); + self.storage.swap_fee.schedule_value_change(new_fee); +} +``` -it is sometimes quite problematic to be unable to read public mutable state in private. for example, a decentralized exchange might have a configurable swap fee that some admin sets, but which needs to be read by users in their private swaps. this is where `DelayedPublicMutable` comes in. +#### `get_current_value` -Delayed Public Mutable is the same as a Public Mutable in that it is a public value that can be read and written, but with a caveat: writes only take effect _after some time delay_. these delays are configurable, but they're typically on the order of a couple hours, if not days, making this state variable unsuitable for actions that must be executed immediately - shut us an emergency shut down. it is these very delays however that enable private contract functions to _read the current value of a public state variable_, which is otherwise typically impossible. +Returns the current value in a public, private or utility execution context. -the existence of minimum delays means that a private function that reads a public value at an anchor block has a guarantee that said historical value will remain the current value until _at least_ some time in the future - before the delay elapses. as long as the transaction gets included in a block before that time (link to the `include_by_timestamp` tx property), the read value is valid. +```rust +#[external("private")] +fn use_swap_fee() { + let current_fee = self.storage.swap_fee.get_current_value(); + // Use the fee in calculations +} +``` ## Private State Variables -these are state variables that have _private_ content, that is, only some people know what is stored in them. these work very differently from public state variables and are unlike anything in languages such as Solidity, since they are built from fundamentally different primitives (notes and nullifiers instead of a key-value updatable public database). +Private state variables have _private_ content meaning that only some people know what is stored in them. These work _very_ differently from public state variables and are unlike anything in languages such as Solidity, since they are built from fundamentally different primitives (UTXO-based notes and nullifiers instead of a key-value updatable public database). + +Aztec.nr provides three private state variable types: -understanding these primitives and how they can be used is key to understanding how private state works. +- `PrivateMutable`: Single mutable private value +- `PrivateImmutable`: Single immutable private value +- `PrivateSet`: Collection of private notes -(table comparing private set and private mutable? not sure what the columns would be) +But, you'll notice that each requires a `NoteType`. To understand this, let's go through notes and nullifiers and how they can be used so we can understand how private state works. ### Notes and Nullifiers -Just as public state is stored in a single public data tree (equivalent to the key-value store that is contract storage on the EVM), private state is stored in two separate trees that have different properties: the note hash tree and the nullifier tree +Just as public state is stored in a single public data tree (equivalent to the `key-value` store used for state on the EVM), private state is stored in two separate trees: + +- The note hash tree: stores hashes of the private data, called notes, which are just structs containing private data, with some methods. +- The nullifier tree: the nullifier for a certain note is deterministic and presence of the nullifier in the nullifier tree determines that the note has been spent/used. #### Notes -notes are user-defined data this meant to be stored privately on the blockchain. a note can represent an amount (e.g. some token balance), an id (e.g. a vote proposal id), an address (e.g. an authorized account), or any kind of private piece of data. +Notes are user-defined data that can be stored privately on the blockchain. A note can represent any private data e.g., an amount (e.g. some token balance), an ID (e.g. a vote proposal Id) or an address (e.g. an authorized account). -they also have some metadata, including a storage slot to avoid collisions with other notes (link above), a 'randomness' value that helps hide the content, and an owner who can nullify the note (more on this later). +They also have some metadata, including a storage slot to avoid collisions with other notes, a `randomness` value that helps hide the content, and an `owner` who can nullify the note. -the note content plus metadata are all hashed together, and it is this hash that gets stored onchain in the note hash tree. the underlying note content (the note hash preimage) is not stored anywhere, and so third parties cannot access it and it remains private. the rightful owner will however be able to use the note in the future by producing the hidden content and showing that its hash is stored onchain as part of a zero-knowledge proof - this is typically referred to as 'reading a note'. +The note content, plus the metadata, are all hashed together, and it is this hash that gets stored on-chain in the note hash tree. This hash is called a commitment. The underlying note content (the note hash preimage) is not stored anywhere on-chain, and so third parties cannot access it and it remains private. -> note: aztecnr comes with some prebuilt note types, like `UintNote` and `AddressNote`, but users are also free to create their own with the `#[note]` macro. (links) +Note: Aztec.nr comes with some prebuilt note types, including [`UintNote`](https://github.com/AztecProtocol/aztec-packages/tree/08935f75dbc3052ce984add225fc7a0dac863050/noir-projects/aztec-nr/uint-note) and [`AddressNote`](https://github.com/AztecProtocol/aztec-packages/tree/08935f75dbc3052ce984add225fc7a0dac863050/noir-projects/aztec-nr/address-note), but users are also free to create their own with the `#[note]` macro. -##### Note Discovery +#### Nullifiers -because notes are private, not even the intended recipient is aware of their existence, and they must be somehow notified. for example, when making a payment and creating a note for the payee with the intended amount, they must be shown the preimage of the note that was inserted in the note hash tree in a given transaction in order to acknowledge the payment. +A nullifier is a value which indicates a resource has been spent. Nullifiers are unique, and the protocol forbids the same nullifier from being inserted into the tree twice. Spending the same resource therefore results in a duplicate nullifier, which invalidates the transaction. -recipients learning about notes created for them is known as 'note discovery', which is a process aztecnr handles efficiently automatically. it does mean however that when a note is created, a _message_ with the content of note is created and needs to be delivered to a recipient via one of multiple means (link to messages). +Most often, nullifiers are used to mark a note as being spent, which prevents note double spends. The nullifier is typically computed as a **hash of the note contents concatenated with a private key of the note's owner**. These values are **immutable**, and only the owner knows their private keys, ensuring both determinism and secrecy. -##### Note Lifecycle +### Note Emissions -notes are more complicated than regular public state, and so it helps to see the different stages one goes through, and when and where each happens. +When working with private state variables, many operations return a `NoteEmission` type rather than the note directly. This is a type-safe wrapper that ensures you explicitly decide whether to emit the note for the recipient to discover, or to discard it. -- creation: an account executing a private contract function creates a new note according to contract logic, e.g. transferring tokens to a recipient. note values (e.g. the token amount) and metadata are set, and the note hash computed and inserted as one of the effects of the transaction (link to protocol docs - tx effects). +#### Why NoteEmission? -- encryption: the content of the note is encrypted with a key only the sender and intended recipient know - no other account can decrypt this message. (link to message layout, how we do secret sharing and encryption) +Private notes need to be communicated to their recipients so they know the note exists and can use it. The `NoteEmission` wrapper forces you to make an explicit choice about how this happens: -- delivery: the encrypted message is delivered to the recipient via some means. options include storing it onchain as a transaction log, or sending it offchain e.g. via email or by having the recipient scan a QR code on the sender's device. (link to delivery details and options) +- **`.emit(recipient, MessageDelivery)`**: Emits the note so the recipient can discover it. You must specify: + - `recipient`: The `AztecAddress` who should receive the note + - `MessageDelivery`: Either `CONSTRAINED_ONCHAIN` (verified in the circuit) or `UNCONSTRAINED_ONCHAIN` (cheaper but less secure) -- insertion: the transaction is sent to the network and gets included in a block. the note hash is inserted into the note hash tree - this is visible to the entire network, but the content of the note remains private. (link to protocol details - note hash tree insertion and tx effects) +- **`.discard()`**: Explicitly discards the note without emitting it (useful when you're reading but not sending) -- discovery: the recipient processes the encrypted message they were sent, decrypting it and finding the note's content (i.e. the hash preimage). they verify that the note's hash exists on chain in the note hash tree. they store the note's content in their own private database, and can now spend the note. (link to message discovery and processing) +#### Accessing the Note -- reading: while executing private contract function, the recipient fetches the note's content and metadata from their private database and shows that its hash exists in the note hash tree as part of the zero-knowledge proof. +After calling `.emit()` or `.discard()`, you can access the underlying note using the `.note` property: -- nullification: the recipient computes the note's nullifier and inserts it as one of the effects of the transaction (link to prot docs tx effects), preventing the note from being read again. +```rust +// Get the note and emit it +let emission = self.storage.user_settings.at(owner).get_note(); +let note = emission.emit(owner, MessageDelivery.CONSTRAINED_ONCHAIN).note; -#### Nullifiers +// Or discard it if you don't need to emit +let note = self.storage.user_settings.at(owner).get_note().discard().note; +``` -the nullifier tree is append-only - if it wasn't, when a note was spent then external observers would notice that the tree leaf inserted in some transaction was modified in a second transaction, therefore linking them together and leaking privacy. it would for example mean that when a user made a payment to a third party, they'd be able to know when the recipient spent the received funds. nullifiers exist to solve the above issue. +Methods that return `NoteEmission` include `initialize()`, `get_note()`, and `replace()` on `PrivateMutable` and `PrivateImmutable`, as well as `insert()` on `PrivateSet`. -a nullifier is a value which indicates a resource has been spent. nullifiers are unique, and the protocol forbids the same nullifier from being inserted into the tree twice. spending the same resource therefore results in a duplicate nullifier, which invalidates the transaction. +### Choosing a Private State Variable -most often, nullifiers are used to mark a note as being spent, which prevents note double spends. this requires two properties from the function that computes a note's nullifier: +Due to the complexities of Aztec's private state model, private state variables do not map 1:1 with public state variables. Understanding these differences between the different private state variables is important when it comes to designing private smart contracts. -- determinism: the nullifier **must** be deterministic given a note, so that the same nullifier value is computed every time the note is attempted to be spent. A non-deterministic nullifier would result in a note being spendable more than once because the nullifiers would not be duplicates. -- secret: the nullifier **must** not be computable by anyone except the owner, _even by someone that knows the full note content_. This is because some third parties _do_ know the note content: when paying someone and creating a note for them, the payer creates the note on their device and thus has access to all of its data and metadata. +Below is a table comparing certain key properties of the different private state variables Aztec.nr offers: -there are multiple ways to compute nullifiers that fulfill this property, but the most widely used one is to have the nullifier be a hash of the note contents concatenated with a private key of the note's owner (link to account keys). These values are immutable, and only the owner knows their private keys, and so both determinism and secrecy are achieved. These nullifiers are sometimes called 'zcash-style nullifiers', because this is the format ZCash uses for theirs. +| State variable | Mutable? | Cost to read? | Writable by third parties? | Example use case | +| ------------------ | -------- | ------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- | +| `PrivateMutable` | yes | yes | no | Mutable user state only accessible by them (e.g. user settings or keys) | +| `PrivateImmutable` | no | no | no | Fixed configuration, one-way actions (e.g. initialization settings for a proposal) | +| `PrivateSet` | yes | yes | yes | Aggregated state others can add to, e.g. token balance (set of amount notes), nft collections (set of nft ids) | -### How aztec-nr Abstracts Private State Variables +### PrivateMutable -and mentioned in notes and nullifiers (link), implementing a private state variable requires careful coordination of multiple primitives and concepts (creating notes, encrypting, delivering, discovering and processing messages, reading notes and computing their nullifiers). aztec-nr provides convenient types and functions that handle all of these low level details in order to allow developers to write safe code without having to understand the nitty-gritty. +`PrivateMutable` is conceptually similar to `PublicMutable` and regular Solidity state variables in that it is a variable that has exactly one value at any point in time that can be read and written. However, for `PrivateMutable`: -by applying the `#[note]` macro to a noir struct, users can define values that will be storable in notes (link to macro docs. also this is a bit of a lie right now, notes also need an owner and randomness, but they soon wont). private state variables can then hold these notes and be used to read, write, and deliver note messages to the intended recipient. +- The value is, of course, _private_, meaning only the account the value belongs to can read it. +- _Only ONE account can read and write the state variable_. It is not possible for example to use a `PrivateMutable` to store user settings and then have some admin account alter these settings. +- Reading the current value results in the state variable being updated, increasing tx costs and requiring delivery of a note message. +- There is no `write` function - the current value is instead `replace`d. -> advanced users can change this default behavior by either defining their own custom note hash and nullifier functions (link to custom notes), implementing their own state variables (link), or even accessing the note hash and nullifiers tree directly (link). +#### Declaration -the snippet below shows a contract with two private state variables: an admin address (stored in an `AddressNote`) and a counter of how many calls the admin has made (stored in a `UintNote`). These values will be private and therefore not known except by the accounts that own these notes (the admin). In the `perform_admin_action` private function, the contract checks that it is being called by the correct admin and updates the call count by incrementing it by one. +```rust +#[storage] +struct Storage { + user_settings: PrivateMutable, +} +``` -(this is not a real snippet, it's missing some small irrelevant details - but the gist of it is correct) +#### `is_initialized` + +An unconstrained method to check whether the `PrivateMutable` has been initialized or not: ```rust -#[note] -struct AddressNote { - value: AztecAddress, +let is_initialized = self.storage.user_settings.at(owner).is_initialized(); +``` + +#### `initialize` + +The `PrivateMutable` should be initialized to create the first note and value: + +```rust +use aztec::messages::message_delivery::MessageDelivery; + +#[external("private")] +fn initialize_settings(value: u8) { + let owner = self.msg_sender(); + let note = SettingsNote::new(value, owner); + self.storage.user_settings.at(owner).initialize(note).emit(owner, MessageDelivery.CONSTRAINED_ONCHAIN); } +``` + +#### `get_note` + +This function allows us to get the note of a `PrivateMutable`, essentially reading the value: + +```rust +#[external("private")] +fn read_settings() -> SettingsNote { + let owner = self.msg_sender(); + self.storage.user_settings.at(owner).get_note().emit(owner, MessageDelivery.CONSTRAINED_ONCHAIN).note +} +``` -#[note] -struct UintNote { - value: u128, +:::info +To ensure that a user's private execution always uses the latest value of a `PrivateMutable`, the `get_note` function will nullify the note that it is reading. This means that if two people are trying to use this function with the same note, only one will succeed. +::: + +#### `replace` + +To update the value of a `PrivateMutable`, we can use the `replace` method: + +```rust +#[external("private")] +fn update_settings(new_value: u8) { + let owner = self.msg_sender(); + self.storage.user_settings.at(owner).replace(|_| SettingsNote::new(new_value, owner)).emit(owner, MessageDelivery.CONSTRAINED_ONCHAIN); } +``` +### PrivateImmutable + +`PrivateImmutable` represents a unique private state variable that, as the name suggests, is immutable. Once initialized, its value cannot be altered. This is the private equivalent of `PublicImmutable`, except the value is only known to its owner. + +#### Declaration + +```rust #[storage] -struct Storage { - admin: PrivateImmutable, - admin_call_count: PrivateMutable, +struct Storage { + signing_key: PrivateImmutable, } +``` +#### `initialize` + +When this function is invoked, it creates a nullifier for the storage slot, ensuring that the `PrivateImmutable` cannot be initialized again: + +```rust #[external("private")] -fn perform_admin_action() { - // Read the contract's admin address and check against the caller - let admin = self.storage.admin.read().value; - assert(self.msg_sender() == admin); - - // Update the call count by replacing (updating - rename soon) the current note with a new one that equals the - // current value + 1 - this requires knowing what the current value is in the first place, i.e. reading the variable. - // - // We then deliver the encrypted message with the note's content to the admin, so that they become aware of the new - // value of the counter and can update it again in the future. - self.storage.admin_call_count - .replace(|current| UintNote{ value: current.value + 1 }) // wouldn't it be great if we didn't have to deal with this wrapping and unwrapping? - .deliver(admin); - - ... +fn initialize_key(key_value: Field) { + let owner = self.msg_sender(); + let note = KeyNote::new(key_value, owner); + self.storage.signing_key.at(owner).initialize(note).emit(owner, MessageDelivery.CONSTRAINED_ONCHAIN); } ``` -### Choosing a Private State Variable +#### `get_note` -due to the complexities of aztec's private state model (link to notes and nullifiers section above), private state variables are not just the same as the public ones except private: they each have their own quirks and trade-offs. understanding these is quite important when it comes to designing private smart contracts and how they'll store data. +Similar to the `PrivateMutable`, we can use the `get_note` method to read the value: -below is a table comparing certain key properties of the different private state variables aztec-nr offers. +```rust +#[external("private")] +fn get_key() -> KeyNote { + let owner = self.msg_sender(); + self.storage.signing_key.at(owner).get_note() +} +``` -| state variable | mutable? | cost to read? | writable by third parties? | example use case | -| ------------------ | -------- | ------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- | -| `PrivateMutable` | yes | yes | no | mutable user state only accessible by them (e.g. user settings or keys) | -| `PrivateImmutable` | no | no | no | fixed configuration, one-way actions (e.g. initialization settings for a proposal) | -| `PrivateSet` | yes | yes | yes | aggregated state others can add to, e.g. token balance (set of amount notes), nft collections (set of nft ids) | +Unlike a `PrivateMutable`, the `get_note` function for a `PrivateImmutable` doesn't nullify the current note. This means that multiple accounts can concurrently call this function to read the value. -### Private Mutable (link to apiref) +### PrivateSet -This is conceptually similar to `PublicMutable` or regular Solidity state variables in that it is a variable that has exactly one value at any point in time that can be read and written. unlike those however, this value is _private_, meaning only the account the value belongs to can read it. +`PrivateSet` is used for managing a collection of notes. Like `PrivateMutable`, this is a private state variable that can be modified. There are two key differences: -There are some other key differences when compared to `PublicMutable`. The most important one is that _only one account can read and write the state variable_. It is not possible for example to use a `PrivateMutable` to store user settings and then have some admin account alter these settings. Allowing this would require that the admin know both the current value of the private state variable _and_ the owner's nullifying secret key, both of which are private information. +- A `PrivateSet` is not a single value but a _set_ (a collection) of values (represented by notes) +- Any account can insert values into someone else's set. -This also means that `PrivateMutable` cannot be used to store things like token balances, which senders would need to update - that is what `PrivateSet` is for (link). +The set's current value is the collection of notes in the set that have not yet been nullified. These notes can have any type: they could be nft IDs, representing a user's nft collection, or they might be token amounts, in which case _the sum_ of all values in the set would be the user's current balance. -The second difference with `PublicMutable` is seen on the API, notably: +#### Declaration -- an initial value must be set via `initialize` (link to apiref section) -- reading the current value results in the state variable being updated, increasing tx costs and requiring delivery of a note message (link to apiref section) -- there is no `write` function - the current value is instead `replace`d (link to apiref section) +For example, to add a mapping of private token balances to storage: -### Private Immutable (link to apiref) +```rust +#[storage] +struct Storage { + balances: Map, Context>, +} +``` -This is the private equivalent of `PublicImmutable` , except the value is only known to its owner. Like `PublicImmutable`, `PrivateImmutable` can be initialized _at any point in time_ during the contract's lifecycle - attempts to read it prior to initialization will result in failed transactions. +#### `insert` -`PrivateImmutable` is convenient in that it creates no transaction effects (like notes, nullifiers or messages) when being read. This makes this state variable very convenient for immutable private configuration, such as account contract signing keys. +Allows us to modify the storage by inserting a note into the `PrivateSet`: -### Private Set (link to apiref) +```rust +#[external("private")] +fn mint_tokens(to: AztecAddress, amount: u128) { + let note = UintNote::new(amount, to); + self.storage.balances.at(to).insert(note).emit(to, MessageDelivery.UNCONSTRAINED_ONCHAIN); +} +``` -Like `PrivateMutable`, this is a private state variable that can be mutated. There are two key differences however: a `PrivateSet` is not a single value but a _set_ (a collection) of values (represented by notes), and any account can insert values into someone else's set. +#### `get_notes` -the set's current value is simply the collection of notes in the set that have not yet been nullified. these notes can have any meaning: they could be nft ids, representing a user's nft collection, or they might be token amounts, in which case _the sum_ of all values in the set would be the user's current balance. +Retrieves notes the account has access to. You can optionally provide filtering options: -aggregated state, like a token user balance as a private set of value notes, benefits greatly from third parties having the capacity to insert into the set. any account can create a note for a recipient (e.g. as part of a token transfer), effectively increasing their balance, _without knowing what the total balance is_ (which would be the case if using `PrivateMutable`). this closely mirrors how fiat cash works (people are given bills/notes without knowledge of the sender of their total wealth), and is also very similar to Bitcoin's UTXO model (except private) or Zcash's notes and nullifiers. +```rust +// Get all notes (with default options) +let options = NoteGetterOptions::new(); +let notes = self.storage.balances.at(owner).get_notes(options); -> note: while the contents of the set are private in the general sense, _some_ accounts do know some of its contents. For example, if account A sends a note of value 20 to B, A will know that at some point in time B held a balance of at least 20. A will however not be able to know when B spends their note due to nullifiers being secret (link to nullifs above). +// Or with custom options (e.g., limit the number of notes) +let options = NoteGetterOptions::new().set_limit(5); +let notes = self.storage.balances.at(owner).get_notes(options); +``` -while users can read any number of values from the set, it is **not possible to guarantee all values have been read**. for example, a user might choose not to reveal some notes, and because they are private this cannot be detected. +#### `pop_notes` -## Containers +This function pops (gets, removes and returns) the notes the account has access to: -these are not state variables themselves, but rather components that store multiple state variables according to some logic +```rust +// Pop notes with a limit +let options = NoteGetterOptions::new().set_limit(10); +let notes = self.storage.balances.at(owner).pop_notes(options); +``` + +#### `remove` + +Will remove a note from the `PrivateSet` if it previously has been read from storage: + +```rust +self.storage.balances.at(owner).remove(note); +``` + +## Containers ### Map -A key-value container that maps keys to state variables - just like Solidity's `mapping`. It can be used with any state variable to create independent instances for each key. +A `Map` is a key-value container that maps keys to state variables - just like Solidity's `mapping`. It can be used with any state variable to create independent instances for each key. + +For example, a `Map>` can be accessed with an address to obtain the `PublicMutable` that corresponds to it. This is exactly equivalent to a Solidity `mapping (address => uint)`. + +#### Declaration + +```rust +#[storage] +struct Storage { + // Map of addresses to public balances + public_balances: Map, Context>, + + // Map of addresses to private note sets + private_balances: Map, Context>, +} +``` + +#### Usage + +Use the `.at()` method to access values by key: + +```rust +#[external("public")] +fn increase_balance(account: AztecAddress, amount: u128) { + let current = self.storage.public_balances.at(account).read(); + self.storage.public_balances.at(account).write(current + amount); +} +``` + +## Custom Structs in Public Storage + +Both `PublicMutable` and `PublicImmutable` are generic over any serializable type, which means you can store custom structs in public storage. + +### Define a Custom Struct + +To use a custom struct in public storage, it must implement the `Packable` trait: + +```rust +use dep::aztec::protocol_types::{ + address::AztecAddress, + traits::{Deserialize, Packable, Serialize} +}; + +#[derive(Deserialize, Packable, Serialize)] +pub struct Asset { + pub interest_accumulator: u128, + pub last_updated_ts: u64, + pub loan_to_value: u128, + pub oracle: AztecAddress, +} +``` + +### Store and Use Custom Structs + +```rust +#[storage] +struct Storage { + assets: Map, Context>, +} + +#[external("public")] +fn update_asset(asset_id: Field, new_accumulator: u128) { + let mut asset = self.storage.assets.at(asset_id).read(); + asset.interest_accumulator = new_accumulator; + self.storage.assets.at(asset_id).write(asset); +} +``` + +## Storage Slots + +Each state variable gets assigned a different numerical value for their **storage slot**. How they are used depends on the kind of state variable: + +- For public state variables, storage slots are related to slots in the public data tree +- For private state variables, storage slots are metadata that gets included in the note hash + +The purpose of slots is the same for both domains: they keep the values of different state values _separate_ so that they do not interfere with one another. -For example, a `Map>` can be accessed with an address to obtain a `PublicMutable` that corresponds to it. This is exactly equivalent to a Solidity `mapping (address => uint)`. +Storage slots are a low-level detail that developers don't typically need to concern themselves with. They are automatically allocated to each state variable by Aztec.nr.