bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 23쪽
p v0.1.4).
```
# Compile your contract first
aztec compile
# Generate a gates flamegraph (requires bb backend)
noir-profiler gates \
--artifact-path ./target/my_contract-MyContract.json \
--backend-path bb \
--output ./target
# Generate an ACIR opcodes flamegraph
noir-profiler opcodes \
--artifact-path ./target/my_contract-MyContract.json \
--output ./target
```
For detailed usage, see the [Noir profiler documentation](https://noir-lang.org/docs/tooling/profiler).
## Understanding kernel overhead[](#understanding-kernel-overhead "Direct link to Understanding kernel overhead")
When you profile a full transaction, you'll see kernel circuits alongside your contract functions. These are protocol overhead — the private kernel runs once per private function call in the transaction. Even a typical transaction calling a single contract function involves two private calls (the account entrypoint + your function), totaling \~427k gates of which only \~14k are your function.
For a detailed breakdown of kernel phases and their gate costs, see [Private Kernel Circuit - Performance Impact](/developers/testnet/docs/foundational-topics/advanced/circuits/private_kernel.md#performance-impact).
## Gate count guidelines[](#gate-count-guidelines "Direct link to Gate count guidelines")
These are rough guidelines for a **single contract function's** gate count (i.e. what `aztec profile gates` reports). A typical transaction (e.g. a token transfer) totals \~500,000 gates across all circuits including kernel overhead, so use that as a reference point.
| Gate Count | Assessment |
| ----------------- | ---------------------------- |
| < 50,000 | Excellent |
| 50,000 - 200,000 | Good |
| 200,000 - 500,000 | Consider optimizing |
| > 500,000 | Worth optimizing if possible |
Note that a high gate count does **not** prevent transaction inclusion — it only affects client-side proving time. See [Private Kernel Circuit - Performance Impact](/developers/testnet/docs/foundational-topics/advanced/circuits/private_kernel.md#performance-impact) for details.
## Next steps[](#next-steps "Direct link to Next steps")
* [Writing efficient contracts](/developers/testnet/docs/aztec-nr/framework-description/advanced/writing_efficient_contracts.md) - optimization strategies and examples
* [Transaction lifecycle](/developers/testnet/docs/foundational-topics/transactions.md)
* [Testing contracts](/developers/testnet/docs/aztec-nr/testing_contracts.md)
---
# Proving historic state
This guide shows you how to prove facts about Aztec's historical state from inside a private function: that a note existed, that a nullifier was or wasn't present, that a contract was deployed, or what a public storage slot held at a past block.
Each proof is a Merkle membership (or non-membership) proof against a state tree root committed in a past block header: the note hash tree, the nullifier tree, or the public data tree. (The Archive tree, by contrast, holds a hash of each block header and is what proves a header is canonical.) Private functions always read from a past block header rather than the live chain tip, because the chain advances while a proof is generated on your device. The proofs therefore tell you what was true once every transaction in the chosen block had executed.
## Prerequisites[](#prerequisites "Direct link to Prerequisites")
* An Aztec contract project set up
* Understanding of Aztec's note and nullifier system
## What you can prove[](#what-you-can-prove "Direct link to What you can prove")
You can create proofs for these elements at any past block height:
* **Note inclusion** - prove a note existed in the note hash tree
* **Note validity** - prove a note existed and wasn't nullified at a specific block
* **Nullifier inclusion/non-inclusion** - prove a nullifier was or wasn't in the nullifier tree
* **Contract deployment** - prove a contract's bytecode was published or initialized
* **Public storage** - read the value a public storage slot held at a past block
Common use cases:
* Verify ownership of an asset from another contract without revealing which specific note
* Prove eligibility based on historical state (e.g., "owned tokens at block X")
* Claim rewards based on past contributions (see the [claim contract](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/claim_contract/src/main.nr) for a complete example)
## Choosing a block header[](#choosing-a-block-header "Direct link to Choosing a block header")
Every function below takes a `BlockHeader`. Two getters on the private context provide one:
* `self.context.get_anchor_block_header()` returns the transaction's anchor block header. The protocol's circuits verify it once per transaction, so using it adds no extra constraints to your function. The protocol requires a transaction to expire within 24 hours of its anchor block, so the anchor is always a block from the last 24 hours.
* `self.context.get_block_header_at(block_number)` returns the header of any block at or before the anchor block, letting you prove against older state at the cost of extra constraints (see [Prove at a specific historical block](#prove-at-a-specific-historical-block)).
Data availability
Producing these proofs requires the historical state trees (note hashes, nullifiers, public storage) for the chosen block. Many nodes prune this data after a few hours, so proving against older blocks requires a node that retains it, such as an archive node.
## Prove note inclusion[](#prove-note-inclusion "Direct link to Prove note inclusion")
Import the function:
history\_import
```
use aztec::history::note::assert_note_existed_by;
```
> [Source code: noir-projects/noir-contracts/contracts/app/claim\_contract/src/main.nr#L19-L21](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/claim_contract/src/main.nr#L19-L21)
Prove a note exists in the note hash tree:
prove\_note\_inclusion
```
let header = self.context.get_anchor_block_header();
let confirmed_note = assert_note_existed_by(header, hinted_note);
```
> [Source code: noir-projects/noir-contracts/contracts/app/claim\_contract/src/main.nr#L55-L58](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/claim_contract/src/main.nr#L55-L58)
## Prove note validity[](#prove-note-validity "Direct link to Prove note validity")
To prove a note was valid (existed AND wasn't nullified) at a historical block:
```
use aztec::history::note::assert_local_note_was_valid_by;
let header = self.context.get_anchor_block_header();
assert_local_note_was_valid_by(header, hinted_note, &mut self.context);
```
This verifies both:
1. The note was included in the note hash tree
2. The note's nullifier was not in the nullifier tree
The `assert_local_note_was_*` helpers only work for the executing contract's own notes: this is because it is not possible for a contract to retrieve the app-siloed nullifier hiding secret key that corresponds to another contract. To prove facts about another contract's notes, use `assert_note_existed_by`, which supports notes of any contract (see [Prove note inclusion](#prove-note-inclusion)).
## Prove at a specific historical block[](#prove-at-a-specific-historical-block "Direct link to Prove at a specific historical block")
To prove against state at a specific past block (not just the anchor block):
```
use aztec::history::note::assert_note_existed_by;
let historical_header = self.context.get_block_header_at(block_number);
assert_note_existed_by(historical_header, hinted_note);
```
warning
Using `get_block_header_at` adds \~3k constraints to prove Archive tree membership. The anchor block header is effectively free since it's verified once per transaction.
## Prove a note was nullified[](#prove-a-note-was-nullified "Direct link to Prove a note was nullified")
To prove a note has been nullified:
```
use aztec::history::note::assert_local_note_was_nullified_by;
let header = self.context.get_anchor_block_header();
assert_local_note_was_nullified_by(header, confirmed_note, &mut self.context);
```
## Prove contract bytecode was published[](#prove-contract-bytecode-was-published "Direct link to Prove contract bytecode was published")
To prove a contract's bytecode was published at a historical block:
```
use aztec::history::deployment::assert_contract_bytecode_was_published_by;
let header = self.context.get_anchor_block_header();
assert_contract_bytecode_was_published_by(header, contract_address);
```
You can also prove a contract was initialized (constructor was called):
```
use aztec::history::deployment::assert_contract_was_initialized_by;
use aztec::oracle::get_contract_instance::get_contract_instance;
let header = self.context.get_anchor_block_header();
let instance = get_contract_instance(contract_address);
assert_contract_was_initialized_by(header, contract_address, instance.initialization_hash);
```
## Read historical public storage[](#read-historical-public-storage "Direct link to Read historical public storage")
To read the value a public storage slot held at a past block in a private function, use `public_storage_historical_read`. It returns the stored value and constrains it against the public data tree root in the given block header:
```
use aztec::history::storage::public_storage_historical_read;
let header = self.context.get_anchor_block_header();
let value = public_storage_historical_read(header, storage_slot, contract_address);
```
An uninitialized slot reads as `0`.
Because this proves the value against a past block header rather than reading the live chain tip, a private function can read public state this way **without enqueuing a public call**. Enqueuing a public call is only needed to read the *current* value or to write to public storage.
Higher-level state variables build on this. Reading a `PublicImmutable` or `DelayedPublicMutable` from a private function performs a historical public storage read internally (through `WithHash`), so you rarely need to call `public_storage_historical_read` directly. Both types are designed so that a historical read is also a correct read of the current value: a `PublicImmutable` can only be initialized once, so its value never changes, while a `DelayedPublicMutable` delays every write and sets the transaction's expiration timestamp so the transaction is only valid for as long as the value it read still holds.
## Available history functions[](#available-history-functions "Direct link to Available history functions")
The `aztec::history` module provides these functions:
| Function | Module | Purpose |
| ----------------------------------------------- | --------------------- | --------------------------------------------------- |
| `assert_note_existed_by` | `history::note` | Prove note exists in note hash tree (any contract) |
| `assert_local_note_was_valid_by` | `history::note` | Prove own note exists and is not nullified |
| `assert_local_note_was_nullified_by` | `history::note` | Prove own note's nullifier is in nullifier tree |
| `assert_local_note_was_not_nullified_by` | `history::note` | Prove own note's nullifier is not in nullifier tree |
| `assert_nullifier_existed_by` | `history::nullifier` | Prove a siloed nullifier exists |
| `assert_nullifier_did_not_exist_by` | `history::nullifier` | Prove a siloed nullifier does not exist |
| `assert_contract_bytecode_was_published_by` | `history::deployment` | Prove a contract's bytecode was published |
| `assert_contract_bytecode_was_not_published_by` | `history::deployment` | Prove a contract's bytecode was not published |
| `assert_contract_was_initialized_by` | `history::deployment` | Prove a contract was initialized |
| `assert_contract_was_not_initialized_by` | `history::deployment` | Prove a contract was not initialized |
| `public_storage_historical_read` | `history::storage` | Read a public storage value at a historical block |
The nullifier functions take a *siloed* nullifier: the nullifier hashed together with the contract address, which is the value actually stored in the global nullifier tree. Use `compute_siloed_nullifier` to convert an inner nullifier (the value passed to `push_nullifier_unsafe`) into its siloed form.
---
# Retrieving and Filtering Notes
This guide shows you how to retrieve and filter notes from private storage using `NoteGetterOptions`.
## Prerequisites[](#prerequisites "Direct link to Prerequisites")
* Aztec contract with note storage
* Understanding of note structure and properties
## Required imports[](#required-imports "Direct link to Required imports")
```
use aztec::note::note_getter_options::{NoteGetterOptions, NoteStatus, SortOrder};
use aztec::utils::comparison::Comparator;
```
## Set up basic note retrieval[](#set-up-basic-note-retrieval "Direct link to Set up basic note retrieval")
### Step 1: Create default options[](#step-1-create-default-options "Direct link to Step 1: Create default options")
```
let mut options = NoteGetterOptions::new();
```
This returns up to `MAX_NOTE_HASH_READ_REQUESTS_PER_CALL` notes without filtering.
### Step 2: Retrieve notes from storage[](#step-2-retrieve-notes-from-storage "Direct link to Step 2: Retrieve notes from storage")
```
// Returns BoundedVec<ConfirmedNote<MyNote>, ...>
let confirmed_notes = storage.my_notes.at(owner).get_notes(options);
```
get\_notes vs pop\_notes
* `get_notes`: Retrieves notes without nullifying. Note data is not guaranteed to be current or non-nullified—use when you only need to read note data without consuming it.
* `pop_notes`: Retrieves AND nullifies notes in one operation. Use when consuming notes (e.g., spending tokens). More efficient than calling `get_notes` followed by manual nullification.
Here's an example of `pop_notes` with filtering from the NFT contract:
pop\_notes
```
let notes = nfts.at(from).pop_notes(NoteGetterOptions::new()
.select(NFTNote::properties().token_id, Comparator.EQ, token_id)
.set_limit(1));
assert(notes.len() == 1, "NFT not found when transferring");
```
> [Source code: noir-projects/noir-contracts/contracts/app/nft\_contract/src/main.nr#L229-L234](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#L229-L234)
## Filter notes by properties[](#filter-notes-by-properties "Direct link to Filter notes by properties")
### Step 1: Select notes with specific field values[](#step-1-select-notes-with-specific-field-values "Direct link to Step 1: Select notes with specific field values")
```
// Assuming MyNote has an 'owner' field
let mut options = NoteGetterOptions::new();
options = options.select(
MyNote::properties().owner,
Comparator.EQ,
owner
);
```
### Step 2: Apply multiple selection criteria[](#step-2-apply-multiple-selection-criteria "Direct link to Step 2: Apply multiple selection criteria")
```
let mut options = NoteGetterOptions::new();
options = options
.select(MyNote::properties().value, Comparator.EQ, value)
.select(MyNote::properties().owner, Comparator.EQ, owner);
```
tip
Chain multiple `select` calls to filter by multiple fields. Remember to call `get_notes(options)` after applying all your selection criteria to retrieve the filtered notes.
## Sort retrieved notes[](#sort-retrieved-notes "Direct link to Sort retrieved notes")
### Sort and paginate results[](#sort-and-paginate-results "Direct link to Sort and paginate results")
```
let mut options = NoteGetterOptions::new();
options = options
.select(MyNote::properties().owner, Comparator.EQ, owner)
.sort(MyNote::properties().value, SortOrder.DESC)
.set_limit(10) // Max 10 notes
.set_offset(20); // Skip first 20
```
## Apply custom filters[](#apply-custom-filters "Direct link to Apply custom filters")
Filter Performance
Database `select` is more efficient than custom filters. Use custom filters only for complex logic.
### Create and use a custom filter[](#create-and-use-a-custom-filter "Direct link to Create and use a custom filter")
custom\_filter
```
pub fn filter_notes_min_sum(
notes: [Option<HintedNote<FieldNote>>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL],
min_sum: Field,
) -> [Option<HintedNote<FieldNote>>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] {
let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL];
let mut sum = 0;
for i in 0..notes.len() {
if notes[i].is_some() & sum.lt(min_sum) {
let hinted_note = notes[i].unwrap_unchecked();
selected[i] = Option::some(hinted_note);
sum += hinted_note.note.value;
}
}
selected
}
```
> [Source code: noir-projects/noir-contracts/contracts/test/pending\_note\_hashes\_contract/src/filter.nr#L4-L22](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/test/pending_note_hashes_contract/src/filter.nr#L4-L22)
Then use it with `NoteGetterOptions`:
```
let options = NoteGetterOptions::with_filter(filter_notes_min_sum, min_value);
```
Note Limits
Maximum notes per call: `MAX_NOTE_HASH_READ_REQUESTS_PER_CALL` (currently 16)
Available Comparators
* `Comparator.EQ`: Equal to
* `Comparator.NEQ`: Not equal to
* `Comparator.LT`: Less than
* `Comparator.LTE`: Less than or equal
* `Comparator.GT`: Greater than
* `Comparator.GTE`: Greater than or equal
## Call from TypeScript[](#call-from-typescript "Direct link to Call from TypeScript")
You can pass comparator values from TypeScript to your contract functions:
```
import { Comparator } from '@aztec-labs/aztec.js/note';
// Pass comparator to a contract function that accepts it as a parameter
await contract.methods.read_notes(Comparator.GTE, 5).simulate({ from: senderAddress });
```
## View notes without constraints[](#view-notes-without-constraints "Direct link to View notes without constraints")
Use `NoteViewerOptions` in unconstrained utility functions to query notes without generating proofs:
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)
Viewer vs Getter
* `NoteGetterOptions`: For constrained private functions with proof generation (max 16 notes)
* `NoteViewerOptions`: For unconstrained utility functions, no proofs (max 10 notes per page via `MAX_NOTES_PER_PAGE`)
## Query notes with different status[](#query-notes-with-different-status "Direct link to Query notes with different status")
### Set status to include nullified notes[](#set-status-to-include-nullified-notes "Direct link to Set status to include nullified notes")
```
let mut options = NoteGetterOptions::new();
options = options.set_status(NoteStatus.ACTIVE_OR_NULLIFIED);
```
Note Status Options
* `NoteStatus.ACTIVE`: Only active (non-nullified) notes (default)
* `NoteStatus.ACTIVE_OR_NULLIFIED`: Both active and nullified notes
## Next steps[](#next-steps "Direct link to Next steps")
* Learn about [custom note implementations](/developers/testnet/docs/aztec-nr/framework-description/custom_notes.md)
* Explore [note discovery mechanisms](/developers/testnet/docs/foundational-topics/advanced/storage/note_discovery.md)
* Understand [partial notes](/developers/test프로젝트로 돌아가기