Aztec 백서

Aztec

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 37쪽

uires calling `.at(owner)` to access the underlying `PrivateSet` for a specific owner. This binds the owner to the state variable instance. #### `get_notes`[​](#get_notes "Direct link to get_notes") Retrieves notes the account has access to. You can optionally provide filtering options. Returns `ConfirmedNote` instances: private\_set\_get\_notes ``` let options = NoteGetterOptions::with_filter(filter_notes_min_sum, amount); // get note (note inserted at bottom of function shouldn't exist yet) let notes = owner_balance.get_notes(options); ``` > [Source code: noir-projects/noir-contracts/contracts/test/pending\_note\_hashes\_contract/src/main.nr#L66-L70](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/main.nr#L66-L70) #### `pop_notes`[​](#pop_notes "Direct link to pop_notes") This function pops (gets, removes and returns) the notes the account has access to. Unlike `get_notes`, this immediately nullifies the notes and returns them directly (not wrapped in `ConfirmedNote`): private\_set\_pop\_notes ``` let options = NoteGetterOptions::new().set_limit(1); let note = owner_balance.pop_notes(options).get(0); ``` > [Source code: noir-projects/noir-contracts/contracts/test/pending\_note\_hashes\_contract/src/main.nr#L146-L149](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/main.nr#L146-L149) #### `remove`[​](#remove "Direct link to remove") Will remove a note from the `PrivateSet` if it previously has been read from storage. Takes a `ConfirmedNote` as returned by `get_notes`: ``` let options = NoteGetterOptions::new(); let confirmed_notes = self.storage.balances.at(owner).get_notes(options); // ... select a note to remove ... self.storage.balances.at(owner).remove(confirmed_notes.get(0)); ``` Note that if you obtained the note via `get_notes`, it's much better to use `pop_notes`, as `pop_notes` results in significantly fewer constraints due to avoiding an extra hash and read request check. ### SinglePrivateMutable and SinglePrivateImmutable[​](#singleprivatemutable-and-singleprivateimmutable "Direct link to SinglePrivateMutable and SinglePrivateImmutable") For contract-wide private values (not per-owner), use `SinglePrivateMutable` or `SinglePrivateImmutable`. These store exactly one value for the entire contract - a global singleton - rather than separate values per owner. | Type | Use Case | Access Pattern | | ---------------------------- | --------------------------------------- | ----------------------- | | `Owned<PrivateMutable<...>>` | Per-owner private state (like balances) | `.at(owner).get_note()` | | `SinglePrivateMutable` | Contract-wide singleton (like admin) | `.get_note()` directly | Since there's only one value at the storage slot, there's no need to specify an owner to look it up: ``` #[storage] struct Storage<Context> { admin: SinglePrivateMutable<AddressNote, Context>, config: SinglePrivateImmutable<ConfigNote, Context>, } // Access directly without .at(owner) let note_message = self.storage.admin.get_note(); let config = self.storage.config.get_note(); ``` When initializing, you still pass an owner address, but this specifies who can decrypt the note, not the storage location: ``` // owner_address determines who can see the note, not where it's stored self.storage.admin.initialize(note, owner_address).deliver(MessageDelivery::onchain_constrained()); ``` warning `SinglePrivateMutable` uses a nullify-and-recreate pattern when reading. Unless the caller is incentivized to deliver the note message correctly, you should use `MessageDelivery::onchain_constrained()` to prevent malicious actors from bricking the contract by failing to deliver the note. ## Containers[​](#containers "Direct link to Containers") ### Map[​](#map "Direct link to Map") 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<AztecAddress, PublicMutable<u128>>` 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[​](#declaration-6 "Direct link to Declaration") ``` #[storage] struct Storage<Context> { // Map of addresses to public balances public_balances: Map<AztecAddress, PublicMutable<u128, Context>, Context>, // Map of addresses to authorized users authorized_users: Map<AztecAddress, PublicMutable<bool, Context>, Context>, } ``` #### Usage[​](#usage "Direct link to Usage") Use the `.at()` method to access values by key: ``` #[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); } ``` note Maps can only be used with public state variables (`PublicMutable`, `PublicImmutable`, `DelayedPublicMutable`) or other `Map`s. For private state, use the `Owned` wrapper described above. ### Owned[​](#owned "Direct link to Owned") The `Owned` wrapper is used with private state variables (`PrivateMutable`, `PrivateImmutable`, and `PrivateSet`) to associate them with a specific owner. This is necessary because private state variables need to know which address owns the notes they manage. #### Declaration[​](#declaration-7 "Direct link to Declaration") ``` #[storage] struct Storage<Context> { // Single owner's private balance balances: Owned<PrivateSet<UintNote, Context>, Context>, // Single owner's private settings user_settings: Owned<PrivateMutable<SettingsNote, Context>, Context>, } ``` #### Usage[​](#usage-1 "Direct link to Usage") Use the `.at(owner)` method to access the underlying state variable for a specific owner: ``` #[external("private")] fn transfer(from: AztecAddress, to: AztecAddress, amount: u128) { // Access the balance for the 'from' address let options = NoteGetterOptions::new(); let notes = self.storage.balances.at(from).pop_notes(options); // Access the balance for the 'to' address let new_note = UintNote { value: amount }; self.storage.balances.at(to).insert(new_note).deliver(MessageDelivery::onchain_unconstrained()); } ``` The `Owned` wrapper is essential for private state variables because it binds the owner's address to the state variable instance, enabling proper note encryption, nullifier computation, and access control. ## Custom Structs in Public Storage[​](#custom-structs-in-public-storage "Direct link to 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[​](#define-a-custom-struct "Direct link to Define a Custom Struct") To use a custom struct in public storage, it must implement the `Packable` trait: ``` use aztec::protocol::{ 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[​](#store-and-use-custom-structs "Direct link to Store and Use Custom Structs") ``` #[storage] struct Storage<Context> { assets: Map<Field, PublicMutable<Asset, Context>, 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[​](#storage-slots "Direct link to 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 variables *separate* so that they do not interfere with one another. 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. Utilizing storage slots directly can be dangerous as it may accidentally result in data collisions across state variables or invariants being broken. In some advanced use cases, it can be useful to have access to these low-level details, such as when implementing [contract upgrades](/developers/testnet/docs/aztec-nr/framework-description/contract_upgrades.md) or when interacting with protocol contracts. --- # Noir VSCode Extension Install the [Noir Language Support extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir) to get syntax highlighting, syntax error detection, and go-to definitions for your Aztec contracts. The extension drives its language server with `nargo`. The Aztec installer ships a bundled `nargo` and exposes it as the `aztec-nargo` symlink on your `PATH`. Bare `nargo` is intentionally not provided so it does not shadow your own install (if any). Verify the symlink is on your `PATH`: ``` which aztec-nargo # expected: $HOME/.aztec/current/bin/aztec-nargo ``` If you have not installed the Aztec toolchain yet, follow [Getting Started on Local Network](/developers/testnet/getting_started_on_local_network.md) first. ## Configure the extension[​](#configure-the-extension "Direct link to Configure the extension") Set the extension's `Noir: Nargo Path` setting to the absolute path printed by `which aztec-nargo` (for example `$HOME/.aztec/current/bin/aztec-nargo`), then reload the window. `aztec-nargo` is a symlink to the bundled `nargo`, so any tool that invokes it speaks plain `nargo` (LSP included). To confirm the extension is using the bundled toolchain, hover over **Nargo** in the VSCode status bar in the bottom right corner: it should show the path you set. If you have your own `nargo` install and want the extension to use that instead, leave `Noir: Nargo Path` empty so the extension auto-discovers `nargo` from your `PATH`. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") * **LSP reports `startFailed` after setting a custom path**: confirm `aztec-nargo` is executable and that the path is correct, reload the window, and check the **Output** panel for the language server log. * **Extension picks up the wrong `nargo`**: the Aztec installer no longer puts bare `nargo` on `PATH`. Set `Noir: Nargo Path` explicitly to `aztec-nargo` (for the bundled version) or to your own install (for any other version). --- # Logging from Contracts Aztec contracts can emit log messages at seven severity levels. Private function logs appear immediately during local simulation in the Private eXecution Environment (PXE), while public function logs are collected and displayed in test mode. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * An Aztec contract project set up with the `aztec-nr` dependency * Basic understanding of [private, public, and utility functions](/developers/testnet/docs/aztec-nr/framework-description/functions/visibility.md) ## Import the logging functions[​](#import-the-logging-functions "Direct link to Import the logging functions") Logging functions live under `aztec::oracle::logging`. Import the specific functions you need: logging\_imports ``` use aztec::oracle::logging::{ debug_log, debug_log_format, error_log, error_log_format, fatal_log, fatal_log_format, info_log, info_log_format, trace_log, trace_log_format, verbose_log, verbose_log_format, warn_log, warn_log_format, }; ``` > [Source code: docs/examples/contracts/logging\_example/src/main.nr#L5-L11](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/logging_example/src/main.nr#L5-L11) Or import only what you need: ``` use aztec::oracle::logging::{info_log, debug_log, debug_log_format}; ``` Old import path removed The previous import path `dep::aztec::oracle::debug_log` has been removed. Update your imports to use `aztec::oracle::logging` instead. ## Log levels[​](#log-levels "Direct link to Log levels") Aztec supports seven log levels, ordered from least to most verbose: | Level | Value | When to use | | --------- | ----- | -------------------------------------------------- | | `fatal` | 1 | Unrecoverable errors that should always be visible | | `error` | 2 | Recoverable errors or unexpected conditions | | `warn` | 3 | Potential issues worth investigating | | `info` | 4 | General operational information | | `verbose` | 5 | Detailed information for troubleshooting | | `debug` | 6 | Development-time debugging output | | `trace` | 7 | Fine-grained tracing of execution flow | When you set `LOG_LEVEL=info`, you see `fatal`, `error`, `warn`, and `info` messages, but `verbose`, `debug`, and `trace` are hidden. Here is an example using all seven levels: log\_all\_levels ``` #[external("private")] fn log_all_levels(value: Field) { fatal_log("fatal level message"); fatal_log_format("fatal: {0}", [value]); error_log("error level message"); error_log_format("error: {0}", [value]); warn_log("warn level message"); warn_log_format("warn: {0}", [value]); info_log("info level message"); info_log_format("info: {0}", [value]); verbose_log("verbose level message"); verbose_log_format("verbose: {0}", [value]); debug_log("debug level message"); debug_log_format("debug: {0}", [value]); trace_log("trace level message"); trace_log_format("trace: {0}", [value]); } ``` > [Source code: docs/examples/contracts/logging\_example/src/main.nr#L48-L66](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/logging_example/src/main.nr#L48-L66) ## Simple log messages[​](#simple-log-messages "Direct link to Simple log messages") Each level has a function that accepts a plain string with no format arguments: log\_simple ``` // Simple messages (no arguments) info_log("Private function called"); debug_log("Checkpoint reached in private function"); ``` > [Source code: docs/examples/contracts/logging\_example/src/main.nr#L23-L27](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/logging_example/src/main.nr#L23-L27) ## Log messages with format arguments[​](#log-messages-with-format-arguments "Direct link to Log messages with format arguments") Each level also has a `_format` variant that accepts a format string and an array of `Field` values. Use `{0}`, `{1}`, etc. to insert individual arguments by index, or `{}` to print the entire array: log\_format\_patterns ``` #[external("private")] fn log_format_patterns(a: Field, b: Field, c: Field) { // Single indexed argument debug_log_format("First value: {0}", [a]); // Multiple indexed arguments info_log_format("Values: {0}, {1}, {2}", [a, b, c]); // Whole array dump debug_log_format("All values: {}", [a, b, c]); } ``` > [Source code: docs/examples/contracts/logging\_example/src/main.nr#L68-L80](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/logging_example/src/main.nr#L68-L80) note Format arguments must be `Field` values. Use `.to_field()` to convert addresses and other types: log\_address ``` #[external("private")] fn log_with_address(sender: AztecAddress) { info_log_format("Sender: {0}", [sender.to_field()]); } ``` > [Source code: docs/examples/contracts/logging\_example/src/main.nr#L33-L38](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/logging_example/src/main.nr#L33-L38) ## Viewing logs[​](#viewing-logs "Direct link to Viewing logs") ### In `aztec test` (Noir tests)[​](#in-aztec-test-noir-tests "Direct link to in-aztec-test-noir-tests") To see contract logs, set `LOG_LEVEL` to include the `debug_log` module: ``` LOG_LEVEL="error;trace:debug_log" aztec test ``` tip Use different log levels strategically: add `info_log` calls for key state transitions you always want to see, and `debug_log` or `trace_log` calls for detailed inspection. ### In TypeScript tests (jest, vitest)[​](#in-typescript-tests-jest-vitest "Direct link to In TypeScript tests (jest, vitest)") TypeScript test environments do not enable contract logs by default. Set the `LOG_LEVEL` environment variable to include the `contract_log` module: ``` # Show contract logs at debug level and above LOG_LEVEL="info;debug:contract_log" yarn test # Show all contract log levels (most verbose) LOG_LEVEL="error;trace:contract_log" yarn test ``` ### With a local network[​](#with-a-local-network "Direct link to With a local network") Contract logs appear in the process that runs the PXE — your test process, not the network process. The network window only shows system-level infrastructure logs (archiver, world-state, etc.), which are generally not useful for contract debugging. When running TypeScript tests against a local network, set `LOG_LEVEL` on the **test command**: ``` # Your test process sees contract logs LOG_LEVEL="error;trace:contract_log" yarn test ``` You do not need to change the `LOG_LEVEL` on `aztec start --local-network` to see contract logs. ## `LOG_LEVEL` syntax reference[​](#log_level-syntax-reference "Direct link to log_level-syntax-reference") The `LOG_LEVEL` environment variable uses a semicolon-delimited format: ``` <default_level>;<level>:<module1>,<module2>;<level>:<module3> ``` * **First segment (required)**: the default log level for all modules. A bare `level:module` with no preceding default (e.g. `LOG_LEVEL="warn:simulator"`) is invalid and throws `Invalid log level` — the parser always reads the segment before the first `;` as the default level. To filter only specific modules, start with `silent` (e.g. `LOG_LEVEL="silent;debug:simulator"`) * **Remaining segments**: `level:module` pairs that override the default for specific modules * Modules are comma-separated within a segment * The `aztec:` prefix is automatically stripped from module names * Module names support regex or prefix matching ### Common configurations[​](#common-configurations "Direct link to Common configurations") | Scenario | `LOG_LEVEL` value | | --------------------------------------- | -------------------------------------------------- | | Contract logs in `aztec test` (TXE) | `error;trace:debug_log` | | Contract logs in TypeScript tests (PXE) | `error;trace:contract_log` | | Contract debug+ logs with system info | `info;debug:contract_log` | | Only contract warnings and errors | `warn;warn:contract_log` | | Everything verbose | `verbose` | | Debug a specific system module | `info;debug:sequencer` | | Multiple module overrides | `warn;debug:sequencer,archiver;trace:contract_log` | ## How contract logs are displayed[​](#how-contract-logs-are-displayed "Direct link to How contract logs are displayed") ### In `aztec test` (TXE)[​](#in-aztec-test-txe "Direct link to in-aztec-test-txe") Contract logs appear under the `debug_log` module: ``` [07:40:29.947] DEBUG: txe:top_level_context:debug_log your message here ``` ### In TypeScript tests (PXE)[​](#in-typescript-tests-pxe "Direct link to In TypeScript tests (PXE)") When running through the PXE, the output includes the contract name with an abbreviated address: ``` [07:40:29.937] INFO: contract_log::Counter(0x1234abcd) 164f9c87bca0cf8c Transfer completed [07:40:29.947] DEBUG: contract_log::Counter(0x1234abcd) 164f9c87bca0cf8c Processing value: 0x2a ``` The hex value after the address (`164f9c87bca0cf8c`) is an internal request identifier. If the contract n
프로젝트로 돌아가기