bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 35쪽
act_address).transfer_in_private_with_offchain_delivery(
owner,
recipient,
transfer_amount,
0,
);
// Transfer tokens. The offchain-delivered notes (change note for the sender, balance note for the recipient,
// Transfer event) end up in TXE's offchain effect buffer.
env.call_private(owner, transfer_call);
// `offchain_messages()` returns up to `MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY` (64), but `offchain_receive` takes at
// most `MAX_OFFCHAIN_MESSAGES_PER_RECEIVE_CALL` (16). This test only produces a handful of messages, so a single
// batch suffices.
let messages = env.offchain_messages();
let mut batch: BoundedVec<_, aztec::messages::processing::offchain::MAX_OFFCHAIN_MESSAGES_PER_RECEIVE_CALL> =
BoundedVec::new();
for i in 0..messages.len() {
batch.push(messages.get(i));
}
env.execute_utility(Token::at(token_contract_address).offchain_receive(batch));
utils::check_private_balance(
env,
token_contract_address,
owner,
mint_amount - transfer_amount,
);
utils::check_private_balance(env, token_contract_address, recipient, transfer_amount);
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/test/transfer\_in\_private\_with\_offchain\_delivery.nr#L6-L43](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_private_with_offchain_delivery.nr#L6-L43)
`env.offchain_messages()` returns up to 64 messages, so drain it into batches of at most 16 when a test emits more messages than one `offchain_receive` call accepts.
## Next steps[](#next-steps "Direct link to Next steps")
* Compare delivery modes and their guarantees in [Note delivery](/developers/testnet/docs/aztec-nr/framework-description/note_delivery.md)
* Learn how onchain-delivered notes are found in [Note discovery](/developers/testnet/docs/foundational-topics/advanced/storage/note_discovery.md)
* Browse the [`MessageDelivery`](/aztec-nr-api/testnet/noir_aztec/messages/delivery/struct.MessageDelivery) API reference
---
# State Variables
A contract's state is defined by multiple values. For example, in a token contract, these include 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.
## Choosing the right storage type[](#choosing-the-right-storage-type "Direct link to Choosing the right storage type")
| Need | Use |
| ----------------------------------------------- | ------------------------------ |
| Public value anyone can read/write | `PublicMutable` |
| Public value set once (contract name, decimals) | `PublicImmutable` |
| Public key-value mapping | `Map<K, PublicMutable<V>>` |
| Private collection per user (token balances) | `Owned<PrivateSet<...>>` |
| Single private value per user | `Owned<PrivateMutable<...>>` |
| Immutable private value per user | `Owned<PrivateImmutable<...>>` |
| Contract-wide private singleton (admin key) | `SinglePrivateMutable` |
| Public value readable in private execution | `DelayedPublicMutable` |
## Prerequisites[](#prerequisites "Direct link to Prerequisites")
* An Aztec contract project set up with `aztec-nr` dependency
* Understanding of Aztec's private and public state model
* Familiarity with Noir struct syntax
For storage concepts, see [storage overview](/developers/testnet/docs/foundational-topics/state_management.md).
## The Storage Struct[](#the-storage-struct "Direct link to The Storage Struct")
State variables are declared in Solidity by simply listing them inside of the contract, like so:
```
contract MyContract {
uint128 public my_public_state_variable;
}
```
In Aztec.nr, we define a [`struct`](https://noir-lang.org/docs/language/data_types/structs) that holds *all* state variables. This struct is called **the storage struct**, and it is identified by having the [`#[storage]` macro](/aztec-nr-api/testnet/noir_aztec/macros/storage/fn.storage) applied to it.
```
use aztec::macros::aztec;
#[aztec]
contract MyContract {
use aztec::macros::storage;
#[storage]
struct Storage<Context> {
// state variables go here e.g, the admin of the contract
admin: PublicMutable<AztecAddress, Context>,
}
}
```
This struct must also have a generic type called `C` or `Context` - an unfortunate boilerplate parameter that provides execution mode information.
The `#[storage]` macro can only be used once, so all contract state must be in a **single** struct.
### Accessing Storage[](#accessing-storage "Direct link to 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.
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 private functions:
```
#[storage]
struct Storage<Context> {
my_public_variable: PublicMutable<Field, Context>,
}
#[external("public")]
fn my_public_function() {
let current = self.storage.my_public_variable.read();
self.storage.my_public_variable.write(current + 1);
}
#[external("private")]
fn my_private_function() {
let current = self.storage.my_public_variable.read(); // compilation error - 'read' is not available in private
self.storage.my_public_variable.write(current + 1); // compilation error - 'write' is not available in private
}
#[external("utility")]
fn my_utility_function() {
let current = self.storage.my_public_variable.read();
self.storage.my_public_variable.write(current + 1); // compilation error - 'write' is not available in utility
}
```
## Public State Variables[](#public-state-variables "Direct link to Public State Variables")
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.
### Choosing a Public State Variable[](#choosing-a-public-state-variable "Direct link to Choosing a Public State Variable")
Public state variables are stored in the network's public storage tree and can only be written to by public contract functions. You can 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 documented in the table below.
Below is a table comparing the key properties of the different public state variables that Aztec.nr offers:
| State variable | Mutable? | Readable in private? | Writable in private? | Example use case |
| ------------------------------------------------------------------------------------------------- | ------------------- | -------------------- | -------------------- | ---------------------------------------------------------------------------------- |
| [`PublicMutable`](/aztec-nr-api/testnet/noir_aztec/state_vars/struct.PublicMutable) | yes | no | no | Configuration of admins, global state (e.g. token total supply, total votes) |
| [`PublicImmutable`](/aztec-nr-api/testnet/noir_aztec/state_vars/struct.PublicImmutable) | no | yes | no | Fixed configuration, one-way actions (e.g. initialization settings for a proposal) |
| [`DelayedPublicMutable`](/aztec-nr-api/testnet/noir_aztec/state_vars/struct.DelayedPublicMutable) | yes (after a delay) | yes | no | Non time sensitive system configuration |
### PublicMutable[](#publicmutable "Direct link to PublicMutable")
`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.
It **cannot be read or written to privately**, but it is possible to have private functions 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<u128>`, is incremented. This would let anyone see how many votes have been cast, while preserving the privacy of the account that cast the vote.
#### Declaration[](#declaration "Direct link to Declaration")
Store mutable public state using `PublicMutable<T>` for values that need to be updated throughout the contract's lifecycle.
For example, storing the address of the collateral asset in a lending contract:
public\_mutable
```
collateral_asset: PublicMutable<AztecAddress, Context>,
```
> [Source code: noir-projects/noir-contracts/contracts/app/lending\_contract/src/main.nr#L46-L48](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L46-L48)
#### `read`[](#read "Direct link to read")
`PublicMutable` variables have a `read` method to read the value at the location in storage:
public\_mutable\_read
```
#[external("public")]
#[view]
fn get_assets() -> pub [AztecAddress; 2] {
[self.storage.collateral_asset.read(), self.storage.stable_coin.read()]
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/lending\_contract/src/main.nr#L273-L279](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L273-L279)
#### `write`[](#write "Direct link to write")
The `write` method on `PublicMutable` variables takes the value to write as an input and saves this in storage:
public\_mutable\_write
```
self.storage.collateral_asset.write(collateral_asset);
```
> [Source code: noir-projects/noir-contracts/contracts/app/lending\_contract/src/main.nr#L74-L76](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L74-L76)
### PublicImmutable[](#publicimmutable "Direct link to PublicImmutable")
`PublicImmutable` is a simplified version of `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.
Due to the value being immutable, you can also 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 user registration status.
#### Declaration[](#declaration-1 "Direct link to Declaration")
For example, in the `Storage` struct in a simple token contract, the name, symbol, and decimals are `PublicImmutable` variables:
public\_immutable
```
symbol: PublicImmutable<FieldCompressedString, Context>,
name: PublicImmutable<FieldCompressedString, Context>,
decimals: PublicImmutable<u8, Context>,
```
> [Source code: noir-projects/noir-contracts/contracts/app/simple\_token\_contract/src/main.nr#L58-L62](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/simple_token_contract/src/main.nr#L58-L62)
#### `initialize`[](#initialize "Direct link to initialize")
This function sets the immutable value. It can only be called once.
public\_immutable\_initialize
```
self.storage.name.initialize(FieldCompressedString::from_string(name));
self.storage.symbol.initialize(FieldCompressedString::from_string(symbol));
self.storage.decimals.initialize(decimals);
```
> [Source code: noir-projects/noir-contracts/contracts/app/simple\_token\_contract/src/main.nr#L68-L72](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/simple_token_contract/src/main.nr#L68-L72)
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`[](#read-1 "Direct link to read-1")
Returns the stored immutable value. This function is available in public, private and utility contexts.
public\_immutable\_read
```
#[external("public")]
#[view]
fn public_get_name() -> FieldCompressedString {
self.storage.name.read()
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/simple\_token\_contract/src/main.nr#L75-L81](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/simple_token_contract/src/main.nr#L75-L81)
### DelayedPublicMutable[](#delayedpublicmutable "Direct link to 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 shutdown. 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 `expiration_timestamp` tx property), the read value is valid.
#### Declaration[](#declaration-2 "Direct link to 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.
delayed\_public\_mutable\_storage
```
// Authorizing a new address has a certain delay before it goes into effect.
pub(crate) global CHANGE_AUTHORIZED_DELAY: u64 = 2 * 60 * 60; // 2 hours
#[storage]
struct Storage<Context> {
// Admin can change the value of the authorized address via set_authorized()
admin: PublicImmutable<AztecAddress, Context>,
authorized: DelayedPublicMutable<AztecAddress, CHANGE_AUTHORIZED_DELAY, Context>,
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/auth\_contract/src/main.nr#L30-L40](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L30-L40)
#### `schedule_value_change`[](#schedule_value_change "Direct link to 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.
schedule\_value\_change
```
#[external("public")]
fn set_authorized(authorized: AztecAddress) {
assert_eq(self.storage.admin.read(), self.msg_sender(), "caller is not admin");
self.storage.authorized.schedule_value_change(authorized);
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/auth\_contract/src/main.nr#L49-L55](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L49-L55)
#### `get_current_value`[](#get_current_value "Direct link to get_current_value")
Returns the current value in a public, private or utility execution context.
get\_current\_value
```
#[external("public")]
#[view]
fn get_authorized() -> AztecAddress {
self.storage.authorized.get_current_value()
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/auth\_contract/src/main.nr#L57-L63](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L57-L63)
Privacy Consideration
Reading `DelayedPublicMutable` in private sets the `expiration_timestamp` property, which may reveal timing information. Choose delays that align with common values to maximize privacy sets.
#### `get_scheduled_value`[](#get_scheduled_value "Direct link to get_scheduled_value")
Returns the scheduled value and when it takes effect:
get\_scheduled\_value
```
#[external("public")]
#[view]
fn get_scheduled_authorized() -> (AztecAddress, u64) {
self.storage.authorized.get_scheduled_value()
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/auth\_contract/src/main.nr#L65-L71](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L65-L71)
## Private State Variables[](#private-state-variables "Direct link to Private State Variables")
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:
* `Owned<PrivateMutable<NoteType, Context>, Context>`: Single mutable private value
* `Owned<PrivateImmutable<NoteType, Context>, Context>`: Single immutable private value
* `Owned<PrivateSet<NoteType, Context>, Context>`: Collection of private notes
These private state variables are "owned" and must be wrapped in the `Owned<>` container, which enables owner-specific access via the `.at(owner)` method. Each also 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[](#notes-and-nullifiers "Direct link to Notes and Nullifiers")
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 managed using 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 the presence of the nullifier in the nullifier tree determines that the note has been spent/used.
Understanding these primitives and how they can be used is key to understanding how private state works.
#### Notes[](#notes "Direct link to Notes")
Notes are user-defined data that can be stored privately on the blockchain. A note can represent any private data, such as 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, a `randomness` value that helps hide the content, and an `owner` who can nullify the note.
The note content plus the metadata are all hashed together, and it is this hash that gets stored onchain in the note hash tree. This hash is called a commitment. The underlying note content (the note hash preimage) is not stored anywhere onchain, so third parties cannot access i프로젝트로 돌아가기