bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 28쪽
ID is used when calculating and verifying the contract's [address](/developers/testnet/docs/foundational-topics/contract_creation.md#instance-address) and remains unchanged even if a contract is upgraded.
## Current class ID[](#current-class-id "Direct link to Current class ID")
When a contract is first deployed, its current class ID equals its original class ID. The current class ID determines which code implementation the contract executes.
During an upgrade:
* The original class ID remains unchanged
* The current class ID is updated to the new implementation
* All contract state and data are preserved
## How to upgrade[](#how-to-upgrade "Direct link to How to upgrade")
Contract upgrades must be initiated by the contract itself calling the `ContractInstanceRegistry`:
```
use aztec::protocol::{
constants::CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS,
contract_class_id::ContractClassId,
};
use contract_instance_registry::ContractInstanceRegistry;
#[external("private")]
fn update_to(new_class_id: ContractClassId) {
self.enqueue(
ContractInstanceRegistry::at(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS)
.update(new_class_id)
);
}
```
info
To use the `ContractInstanceRegistry`, add this dependency to your `Nargo.toml`:
```
contract_instance_registry = { git="https://github.com/aztec-labs-eng/aztec-node/", tag="v6.0.0-rc.1", directory="noir-projects/noir-contracts/contracts/protocol_interface/contract_instance_registry_interface" }
```
The `update` function in the registry is a public function, so you can enqueue it from a private function (as shown above) or call it directly from a public function.
Access Control
The example `update_to` function above has no access control, meaning anyone could call it to upgrade your contract. Production contracts should implement proper authorization checks to secure against malicious upgrades.
Contract upgrades use a `DelayedPublicMutable` storage variable in the `ContractInstanceRegistry`, applying to both public and private functions. Upgrades have a delay before taking effect. The default delay is `86400` seconds (one day) but can be configured:
```
#[external("private")]
fn set_update_delay(new_delay: u64) {
self.enqueue(
ContractInstanceRegistry::at(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS)
.set_update_delay(new_delay)
);
}
```
The `new_delay` parameter is in seconds. Changing the update delay is also subject to the previous delay, so the first delay change takes `86400` seconds to take effect.
info
The minimum update delay is `600` seconds.
### Transaction expiration[](#transaction-expiration "Direct link to Transaction expiration")
When sending a transaction, the expiration timestamp is calculated as the current block timestamp plus the minimum update delay of all contracts you interact with. For example:
* If you interact with contracts having delays of 1000 and 10000 seconds, expiration is current timestamp + 1000 seconds
* If a contract has a pending upgrade in 100 seconds, expiration would be current timestamp + 99 seconds
Other `DelayedPublicMutable` storage variables in your transaction may reduce the expiration timestamp further.
note
Only deployed contract instances can upgrade or change their upgrade delay. This restriction may be lifted in the future.
### Upgrade process[](#upgrade-process "Direct link to Upgrade process")
1. **Register the new implementation**: Register the new contract class if it contains public functions. The new implementation must maintain state variable compatibility with the original contract.
2. **Perform the upgrade**: Call the update function with the new contract class ID. The contract's original class ID remains unchanged while the current class ID updates to the new implementation.
3. **Wait for the delay**: The upgrade takes effect after the configured delay period.
4. **Verify the upgrade**: After the delay, the contract executes functions from the new implementation. The contract address remains the same since it's based on the original class ID.
### Interacting with an upgraded contract[](#interacting-with-an-upgraded-contract "Direct link to Interacting with an upgraded contract")
The PXE stores contract instances and classes locally. After a contract upgrades, you must register the new artifact with the wallet before interacting with it:
```
import { getContractClassFromArtifact } from '@aztec-labs/aztec.js/contracts';
import { publishContractClass } from '@aztec-labs/aztec.js/deployment';
// Deploy the original contract (use .wait() to get both contract and instance)
const { contract, instance } = await UpdatableContract.deploy(wallet, ...args)
.send({ from: accountAddress })
.wait();
// Publish the new contract class (required before upgrading)
await (await publishContractClass(wallet, UpdatedContractArtifact))
.send({ from: accountAddress })
.wait();
// Get the new contract class ID
const updatedContractClassId = (
await getContractClassFromArtifact(UpdatedContractArtifact)
).id;
// Trigger the upgrade
await contract.methods
.update_to(updatedContractClassId)
.send({ from: accountAddress })
.wait();
// Wait for the upgrade delay to pass...
// Register the new artifact with the wallet
await wallet.registerContract(instance, UpdatedContract.artifact);
// Create a contract instance with the new artifact
const updatedContract = UpdatedContract.at(contract.address, wallet);
```
If you try to register a contract artifact that doesn't match the current contract class, the registration will fail.
---
# Custom notes
This guide shows you how to create custom note types for storing specialized private data in your Aztec contracts.
## Prerequisites[](#prerequisites "Direct link to Prerequisites")
* Basic understanding of [Aztec private state and notes](/developers/testnet/docs/foundational-topics/state_management.md)
* Aztec development environment set up
## When to create custom notes[](#when-to-create-custom-notes "Direct link to When to create custom notes")
You may want to create your own note type if you need to:
* Store specific data types not provided by built-in note libraries
* Combine multiple fields into a single note (e.g., game cards with multiple attributes)
* Implement custom nullifier schemes for advanced use cases
Built-in Note Types
Aztec.nr provides pre-built note types for common use cases:
**UintNote** - For numeric values like token balances (supports partial notes):
```
# In Nargo.toml
uint_note = { git="https://github.com/aztec-labs-eng/aztec-nr", tag="v6.0.0-rc.1", directory="uint-note" }
```
**FieldNote** - For storing single Field values:
```
# In Nargo.toml
field_note = { git="https://github.com/aztec-labs-eng/aztec-nr", tag="v6.0.0-rc.1", directory="field-note" }
```
**AddressNote** - For storing Aztec addresses:
```
# In Nargo.toml
address_note = { git="https://github.com/aztec-labs-eng/aztec-nr", tag="v6.0.0-rc.1", directory="address-note" }
```
## Creating a custom note[](#creating-a-custom-note "Direct link to Creating a custom note")
Define your custom note with the `#[note]` macro:
nft\_note\_struct
```
use aztec::{macros::notes::note, protocol::traits::Packable};
#[derive(Eq, Packable)]
#[note]
pub struct NFTNote {
pub token_id: Field,
}
```
> [Source code: docs/examples/contracts/nft/src/nft.nr#L1-L9](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/nft/src/nft.nr#L1-L9)
The `#[note]` macro generates the following for your struct:
* `NoteType` trait - Provides a unique type ID for the note
* `NoteHash` trait - Handles note hash and nullifier computation
* `NoteProperties` - Enables field selection when querying notes
### Required traits[](#required-traits "Direct link to Required traits")
Your note struct must derive:
* `Packable` - Required by the `#[note]` macro for note hash computation. You can manually implement this for tighter packing — see [Data Packing and Serialization](/developers/testnet/docs/aztec-nr/framework-description/data_packing.md).
* `Eq` - Required by storage types like `PrivateSet` for note comparisons
The `#[note]` macro handles the `NoteType`, `NoteHash`, and `NoteProperties` traits automatically.
### How note hashing works[](#how-note-hashing-works "Direct link to How note hashing works")
When a note is inserted, the `#[note]` macro generates code that computes the note hash by combining:
1. **Your packed note data** - The fields you define in your struct
2. **Owner address** - Provided by the storage variable
3. **Storage slot** - Determined by the storage layout
4. **Randomness** - Generated automatically to prevent brute-force attacks
This happens automatically - you don't need to include owner or randomness fields in your struct.
## Using notes in storage[](#using-notes-in-storage "Direct link to Using notes in storage")
Notes are stored using `Owned<PrivateSet<...>>` which manages note ownership:
```
use aztec::{
macros::storage::storage,
state_vars::{Owned, PrivateSet},
};
#[storage]
struct Storage<Context> {
// Collection of notes, indexed by owner
nfts: Owned<PrivateSet<NFTNote, Context>, Context>,
}
```
### Inserting notes[](#inserting-notes "Direct link to Inserting notes")
mint
```
#[external("private")]
fn mint(to: AztecAddress, token_id: Field) {
assert(
self.storage.minter.read().eq(self.msg_sender()),
"caller is not the authorized minter",
);
// we create an NFT note and insert it to the PrivateSet - a collection of notes meant to be read in private
let new_nft = NFTNote { token_id };
self.storage.owners.at(to).insert(new_nft).deliver(MessageDelivery::onchain_constrained());
// calling the internal public function above to indicate that the NFT is taken
self.enqueue_self._mark_nft_exists(token_id, true);
}
```
> [Source code: docs/examples/contracts/nft/src/main.nr#L52-L67](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/nft/src/main.nr#L52-L67)
### Reading and removing notes[](#reading-and-removing-notes "Direct link to Reading and removing notes")
Use `pop_notes` to read and nullify notes atomically. This is the recommended pattern for most use cases:
burn
```
#[external("private")]
fn burn(from: AztecAddress, token_id: Field) {
assert(
self.storage.minter.read().eq(self.msg_sender()),
"caller is not the authorized minter",
);
// from the NFTNote properties, selects token_id and compares it against the token_id to be burned
let options = NoteGetterOptions::new()
.select(NFTNote::properties().token_id, Comparator.EQ, token_id)
.set_limit(1);
let notes = self.storage.owners.at(from).pop_notes(options);
assert(notes.len() == 1, "NFT not found");
self.enqueue_self._mark_nft_exists(token_id, false);
}
```
> [Source code: docs/examples/contracts/nft/src/main.nr#L77-L94](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/nft/src/main.nr#L77-L94)
warning
There's also a `get_notes` function that reads without nullifying, but use it with caution - the returned notes may have already been spent in another transaction.
## Custom note hashing[](#custom-note-hashing "Direct link to Custom note hashing")
Most notes should use the standard `#[note]` macro. Use `#[custom_note]` only when you need:
* Custom nullifier schemes (e.g., notes spendable by anyone with a secret, not tied to an owner)
* Partial notes that can be completed in public execution
* Non-standard hash computation for specific security requirements
With `#[custom_note]`, you must implement the `NoteHash` trait yourself:
```
use aztec::{
context::PrivateContext,
keys::getters::{get_nhk_app, get_public_keys, try_get_public_keys},
macros::notes::custom_note,
note::note_interface::NoteHash,
protocol::{
address::AztecAddress,
constants::{DOM_SEP__NOTE_HASH, DOM_SEP__NOTE_NULLIFIER},
hash::poseidon2_hash_with_separator,
traits::Packable,
},
};
#[derive(Eq, Packable)]
#[custom_note]
pub struct CustomHashNote {
pub data: Field,
}
impl NoteHash for CustomHashNote {
fn compute_note_hash(
self,
owner: AztecAddress,
storage_slot: Field,
randomness: Field,
) -> Field {
// Custom hash computation
poseidon2_hash_with_separator(
[self.data, owner.to_field(), storage_slot, randomness],
DOM_SEP__NOTE_HASH,
)
}
fn compute_nullifier(
self,
context: &mut PrivateContext,
owner: AztecAddress,
note_hash_for_nullification: Field,
) -> Field {
// Standard nullifier using owner's nullifier hiding key
let owner_npk_m_hash = get_public_keys(owner).npk_m_hash;
let secret = context.request_nhk_app(owner_npk_m_hash);
poseidon2_hash_with_separator(
[note_hash_for_nullification, secret],
DOM_SEP__NOTE_NULLIFIER,
)
}
unconstrained fn compute_nullifier_unconstrained(
self,
owner: AztecAddress,
note_hash_for_nullification: Field,
) -> Option<Field> {
try_get_public_keys(owner).map(|public_keys| {
let secret = get_nhk_app(public_keys.npk_m_hash);
poseidon2_hash_with_separator(
[note_hash_for_nullification, secret],
DOM_SEP__NOTE_NULLIFIER,
)
})
}
}
```
Naming note
The secret returned by `request_nhk_app` is the **nullifier hiding key** (abbreviated `nhk`). Older docs and code comments may call it the "nullifier secret key" (`nsk`) — these refer to the same key. Always use `request_nhk_app()` rather than computing this key yourself.
## Viewing notes (unconstrained)[](#viewing-notes-unconstrained "Direct link to Viewing notes (unconstrained)")
For read-only queries without constraints:
view\_notes
```
#[external("utility")]
unconstrained fn get_private_nfts(owner: AztecAddress, page_index: u32) -> ([Field; MAX_NOTES_PER_PAGE], bool) {
let offset = page_index * MAX_NOTES_PER_PAGE;
let options = NoteViewerOptions::new().set_offset(offset);
let notes = self.storage.private_nfts.at(owner).view_notes(options);
let mut owned_nft_ids = [0; MAX_NOTES_PER_PAGE];
for i in 0..options.limit {
if i < notes.len() {
owned_nft_ids[i] = notes.get_unchecked(i).token_id;
}
}
let page_limit_reached = notes.len() == options.limit;
(owned_nft_ids, page_limit_reached)
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/nft\_contract/src/main.nr#L269-L286](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L269-L286)
## Further reading[](#further-reading "Direct link to Further reading")
* [What the `#[note]` macro does](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md#implementing-notes)
* [Note getter options](/developers/testnet/docs/aztec-nr/framework-description/advanced/how_to_retrieve_filter_notes.md)
* [Storage types](/developers/testnet/docs/foundational-topics/state_management.md)
* [Macros reference](/developers/testnet/docs/aztec-nr/framework-description/macros.md)
---
# Data Packing and Serialization
Aztec contracts use two separate encoding schemes to convert structs into `Field` arrays. This page tells you which one to reach for and when.
* **`Serialize` / `Deserialize`**: ABI encoding. Used anywhere a value crosses the contract boundary (function arguments, return values, events). The layout must match Noir's intrinsic format, so you almost never hand-roll it.
* **`Packable`**: Storage encoding. Used wherever data is written to state or hashed into notes. The format is internal to your contract, so you can pack multiple small values into a single `Field` to save gas and proving time.
Picking the wrong trait, or missing a chance to pack, can waste gas, storage slots, and proving time.
## When to use Serialize and Deserialize[](#when-to-use-serialize-and-deserialize "Direct link to When to use Serialize and Deserialize")
`Deserialize` is needed for any struct accepted as a function argument; `Serialize` is needed for any struct returned from a function or emitted as an event. Because args and returns often share the same struct, `#[derive(Serialize, Deserialize)]` is the convenient default.
The encoding must follow Noir's intrinsic serialization: each struct member becomes one or more `Field` values, with no packing or compression. When a transaction calls a public function, TypeScript serializes the arguments into an initial witness using Noir's built-in format. If your Noir-side implementation produces a different layout, you get an "arguments hash mismatch" error.
```
// Matches Noir's intrinsic format automatically.
#[derive(Serialize, Deserialize)]
struct MyArgs {
amount: u128, // 1 Field
enabled: bool, // 1 Field
owner: Field, // 1 Field
}
// Serialize::N = 3 (one Field per member)
```
For events, `#[event]` auto-derives `Serialize` for you. You typically do not need `Deserialize` or `Packable` on events.
warning
Do not hand-roll `Serialize` or `Deserialize` for types passed as function arguments. The encoding must match what TypeScript sends, and the derive macro ensures this automatically.
## When to use Packable[](#when-to-use-packable "Direct link to When to use Packable")
Use `Packable` for note `structs` when creating custom notes or as the data type of a state variable (`PublicMutable<T>`, `PublicImmutable<T>`, `DelayedPublicMutable<T>`). `Packable` defines how the value is encoded when written to storage or hashed into a note. It never needs to match any external format; it only needs to roundtrip: `unpack(pack(x)) == x`.
There are two cases.
### Case 1: a custom note[](#case-1-a-custom-note "Direct link to Case 1: a custom note")
`#[note]` *requires* the struct to implement `Packable` but does **not** add it for you. Place `#[derive(Packable)]` on the struct before applying `#[note]`, or the macro will fail compilation with an explicit message.
When a note's members are already `Field`-sized, deriving is enough:
field\_like\_note
```
// A note whose members are already Field-sized.
// #[note] requires Packable; derive is sufficient here -- N = 1.
#[derive(Deserialize, Eq, Packable, Serialize)]
#[note]
pub struct OwnerNote {
pub owner: AztecAddress,
}
```
> [Source code: docs/examples/contracts/packing\_example/src/types.nr#L20-L28](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/packing_example/src/types.nr#L20-L28)
`Eq` is a Noir standard trait for equality comparisons (see [Noir's `Eq` trait](https://noir-lang.org/docs/language/traits)). `#[note]` does not require it, but deriving it is idiomatic because it enables `assert_eq` in tests and note-equality checks. `Serialize` and `Deserialize` are similarly optional here, and useful when a note type crosses a function boundary.
This is how the built-in note types work too: [`AddressNote`](/aztec-nr-api/testnet/address_note/struct.AddressNote) and [`FieldNote`](/aztec-nr-api/testnet/field_note/struct.FieldNote) both derive `Packable` directly because their members are already `Field` or `AztecAddress`.
When a note has members smaller than a `Field` (`bool`, `u8`, `u32`, `u64`), you can skip the `Packable` derive and write a custom implementation that packs multiple values into a single `Field`:
card\_note
```
// A note with two u32 members. Derived Packable would give N = 2;
// a custom impl halves that to N = 1, reducing note-hash inputs.
#[derive(Eq)]
#[note]
pub struct CardNote {
pub strength: u32,
pub points: u32,
}
impl Packable for CardNote {
let N: u32 = 1;
fn pack(self) -> [Field; Self::N] {
[(self.strength as Field) * 2.pow_32(32) + (self.points as Field)]
}
fn unpack(packed: [Field; Self::N]) -> Self {
let points = packed[0] as u32;
let strength = ((packed[0] - points as Field) / 2.pow_32(32)) as u32;
Self { strength, points }
}
}
```
> [Source code: docs/examples/contracts/packing\_example/src/types.nr#L30-L53](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/프로젝트로 돌아가기