bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 38쪽
ame cannot be resolved, you see `Unknown` in its place.
## Logging in public functions[](#logging-in-public-functions "Direct link to Logging in public functions")
Private and public functions handle logging differently:
* **Private functions** execute locally in the PXE. You see logs immediately during simulation.
* **Public functions** execute on the sequencer. You see logs during `.simulate()` calls and after `.send().wait()` completes in test mode.
The logging API is the same in public functions:
log\_public
```
#[external("public")]
fn log_public(value: Field) {
info_log("Public function called");
debug_log_format("Public value: {0}", [value]);
}
```
> [Source code: docs/examples/contracts/logging\_example/src/main.nr#L40-L46](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/logging_example/src/main.nr#L40-L46)
### Accessing logs programmatically[](#accessing-logs-programmatically "Direct link to Accessing logs programmatically")
In test mode (when not using real proofs), you can access public function debug logs on the `TxReceipt`:
```
import { applyStringFormatting } from '@aztec-labs/foundation/log';
const { receipt } = await contract.methods.myPublicFunction(args).send({
from: address,
fee: { paymentMethod },
wait: { timeout: 600 },
});
// Logs are automatically printed to your console.
// You can also access them programmatically:
if (receipt.debugLogs) {
for (const log of receipt.debugLogs) {
console.log(`[${log.level}] ${applyStringFormatting(log.message, log.fields)}`);
}
}
```
Each entry contains:
* `contractAddress` - the contract that emitted the log
* `level` - the log level (`info`, `debug`, etc.)
* `message` - the unformatted message string
* `fields` - the raw `Field` values passed as arguments
warning
`receipt.debugLogs` is only available in test mode (when not using real proofs). In production, debug log collection is disabled.
## Verify logging works[](#verify-logging-works "Direct link to Verify logging works")
Add a `debug_log` call to any contract function, then run with logging enabled:
```
LOG_LEVEL="error;trace:debug_log" aztec test
```
You should see output like:
```
[07:40:29.947] DEBUG: txe:top_level_context:debug_log your message here
```
If no output appears, check the troubleshooting section below.
## Troubleshooting[](#troubleshooting "Direct link to Troubleshooting")
| Problem | Solution |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No contract logs appear in `aztec test` | Set `LOG_LEVEL` to include `debug_log`, e.g., `LOG_LEVEL="error;trace:debug_log" aztec test`. Also verify you are calling a log function inside the contract function being tested. |
| No contract logs in TypeScript tests | Set `LOG_LEVEL` to include `contract_log`, e.g., `LOG_LEVEL="error;trace:contract_log" yarn test`. |
| Import error on `dep::aztec::oracle::debug_log` | This path was removed. Update to `use aztec::oracle::logging::{debug_log, debug_log_format};`. |
| `receipt.debugLogs` is `undefined` | Debug logs are only collected in test mode (non-real-proofs). They are not available in production. |
| Too much noise in log output | Narrow the default level and use module filters, e.g., `LOG_LEVEL="error;debug:contract_log"`. |
## Quick reference[](#quick-reference "Direct link to Quick reference")
| Task | Code or command |
| --------------------------- | ------------------------------------------------------------ |
| Import logging | `use aztec::oracle::logging::{debug_log, debug_log_format};` |
| Simple log | `debug_log("message");` |
| Log with values | `debug_log_format("val: {0}", [my_field]);` |
| Run Noir tests with logs | `LOG_LEVEL="error;trace:debug_log" aztec test` |
| JS tests with contract logs | `LOG_LEVEL="error;trace:contract_log" yarn test` |
## Next steps[](#next-steps "Direct link to Next steps")
* [Debugging Aztec Code](/developers/testnet/docs/aztec-nr/debugging.md) for error codes, profiling, and common issues
* [Events and Logs](/developers/testnet/docs/aztec-nr/framework-description/events_and_logs.md) for emitting events that offchain applications can consume
* [Testing Contracts](/developers/testnet/docs/aztec-nr/testing_contracts.md) for writing and running contract tests
---
# Aztec Contract Standards
Aztec contract standards define shared interfaces and behaviors for common onchain primitives. They serve the same role that ERC standards play on Ethereum: establishing conventions that allow contracts, wallets, and tooling to interoperate without prior coordination.
The standards described in this section are maintained by [DeFi Wonderland](https://github.com/defi-wonderland/aztec-standards) in the `aztec-standards` repository. Each standard is identified by an **Aztec Improvement Proposal (AIP)** number that mirrors its Ethereum counterpart where applicable (AIP-20 corresponds to ERC-20, AIP-721 to ERC-721, AIP-4626 to ERC-4626).
Because Aztec contracts have both private and public execution contexts, the standards are more involved than their Ethereum equivalents. Transfers can move value between private notes and public balances, and many operations require coordination between encrypted state and transparent state within a single transaction.
note
The code examples in this section are taken from the [aztec-standards repository](https://github.com/defi-wonderland/aztec-standards) maintained by DeFi Wonderland. They will differ from the reference contract implementations shipped in the [aztec-packages repo](https://github.com/AztecProtocol/aztec-packages) under `noir-projects/noir-contracts/contracts/`. When in doubt, consult the aztec-standards github repo for the canonical standard interfaces.
## Standards[](#standards "Direct link to Standards")
* [AIP-20: Fungible Token](/developers/testnet/docs/aztec-nr/standards/aip-20.md) — private and public balances, partial-note transfers, recursive note consumption
* [AIP-721: Non-Fungible Token](/developers/testnet/docs/aztec-nr/standards/aip-721.md) — private NFT ownership, partial-note support, commitment-based transfers
* [AIP-4626: Tokenized Vault](/developers/testnet/docs/aztec-nr/standards/aip-4626.md) — yield-bearing vaults with share conversion across private and public contexts
* [Escrow](/developers/testnet/docs/aztec-nr/standards/escrow.md) — minimal token/NFT custody with salt-based authorization
* [Generic Proxy](/developers/testnet/docs/aztec-nr/standards/generic-proxy.md) — forwarding layer for account abstraction patterns
* [Dripper](/developers/testnet/docs/aztec-nr/standards/dripper.md) — development faucet for testing
## Related tutorials[](#related-tutorials "Direct link to Related tutorials")
* [Private Token Contract](/developers/testnet/docs/tutorials/contract_tutorials/token_contract.md) — build a privacy-preserving fungible token that closely parallels AIP-20
* [NFT Bridge](/developers/testnet/docs/tutorials/js_tutorials/token_bridge.md) — build a private NFT with custom `NFTNote` and `PrivateSet`, covering patterns extended by AIP-721
* [Deploying a Token Contract](/developers/testnet/docs/tutorials/js_tutorials/aztecjs-getting-started.md) — deploy and interact with the reference token contract using Aztec.js
* [Counter Contract](/developers/testnet/docs/tutorials/contract_tutorials/counter_contract.md) — introduces private state, notes, and balance management
For the canonical implementations and latest interface specifications, refer to the [aztec-standards repository](https://github.com/defi-wonderland/aztec-standards) maintained by DeFi Wonderland.
---
# AIP-20: Fungible Token
[Source](https://github.com/defi-wonderland/aztec-standards/tree/dev/src/token_contract)
AIP-20 defines a fungible token with support for private balances (stored as notes in the note hash tree), public balances (stored in contract public storage), and a hybrid transfer path between the two.
## Storage layout[](#storage-layout "Direct link to Storage layout")
The token contract stores its name, symbol, and decimals as immutable public fields. Private balances are held in an `Owned<BalanceSet>` that restricts note access to the balance owner. Public balances use a simple `Map` keyed by address.
```
#[storage]
struct Storage<Context> {
name: PublicImmutable<FieldCompressedString, Context>,
symbol: PublicImmutable<FieldCompressedString, Context>,
decimals: PublicImmutable<u8, Context>,
private_balances: Owned<BalanceSet<Context>, Context>,
total_supply: PublicMutable<u128, Context>,
public_balances: Map<AztecAddress, PublicMutable<u128, Context>, Context>,
minter: PublicImmutable<AztecAddress, Context>,
upgrade_authority: PublicImmutable<AztecAddress, Context>,
asset: PublicImmutable<AztecAddress, Context>,
vault_offset: PublicImmutable<u128, Context>,
}
```
The `asset` and `vault_offset` fields exist to support the [AIP-4626 vault pattern](/developers/testnet/docs/aztec-nr/standards/aip-4626.md). A standalone AIP-20 token that is not used as a vault underlying asset does not need to populate these fields.
## Note count constants[](#note-count-constants "Direct link to Note count constants")
In Aztec, every time a user receives private tokens, a new encrypted note is added to their balance. Over time, a user's balance can be spread across dozens of small notes. A transfer must consume enough of these notes to cover the amount, but each note consumed adds computational overhead (gates) to the zero-knowledge proof the user's device must generate. Without a bound, a single transfer could take minutes to prove. Two constants cap how many notes a single proof handles, keeping proving times practical:
```
global INITIAL_TRANSFER_CALL_MAX_NOTES: u32 = 2;
global RECURSIVE_TRANSFER_CALL_MAX_NOTES: u32 = 8;
```
The initial call attempts to settle the transfer with at most two notes. If that is not enough to cover the amount, the contract recurses into itself and tries up to eight notes per recursive call.
A **placeholder address** is used in partial-note flows to signal that a transfer destination is not yet known at the time the sender initiates the operation. This distinguishes "recipient not yet determined" from "recipient is the zero address," and allows offchain indexers to detect [partial-note transfers](#partial-note-transfers) in event logs without decrypting the note contents:
```
global PRIVATE_ADDRESS_MAGIC_VALUE: AztecAddress =
AztecAddress::from_field(0x1ea7e01501975545617c2e694d931cb576b691a4a867fed81ebd3264);
```
## Partial-note transfers[](#partial-note-transfers "Direct link to Partial-note transfers")
AIP-20 supports partial-note (or "commitment-based") transfers. In Aztec, private functions execute on the user's device before the transaction reaches the network, so they cannot read public state (like a DEX order book or auction result). Partial notes solve this by splitting the operation: the sender privately locks funds into a commitment, and later a public function — which *can* read public state — completes the transfer to the correct recipient. This is what makes private DeFi composability possible.
Concretely, the sender locks funds in a note whose destination address is not yet known. A completer — typically a contract acting as a relayer or settlement layer — later fills in the recipient and finalizes the note.
The sender calls `initialize_transfer_commitment` to create the commitment:
```
#[external("private")]
fn initialize_transfer_commitment(to: AztecAddress, completer: AztecAddress) -> Field {
let commitment = self.internal._initialize_transfer_commitment(to, completer);
commitment.to_field()
}
```
The returned `Field` is an opaque commitment to the destination and completer. A separate call then subtracts the balance and completes the note:
```
#[external("private")]
fn transfer_private_to_commitment(
from: AztecAddress,
commitment: Field,
amount: u128,
_nonce: Field,
) {
_validate_from_private::<4>(self.context, from);
self.internal._decrease_private_balance(from, amount, INITIAL_TRANSFER_CALL_MAX_NOTES);
let completer = self.msg_sender();
PartialUintNote::from_field(commitment).complete_from_private(
self.context,
completer,
amount,
);
}
```
This two-step design is useful in DeFi protocols where the recipient of funds depends on some offchain or asynchronous computation.
## Recursive balance subtraction[](#recursive-balance-subtraction "Direct link to Recursive balance subtraction")
When `INITIAL_TRANSFER_CALL_MAX_NOTES` notes are insufficient to cover a transfer, the contract calls itself recursively until the full amount is consumed:
```
#[internal("private")]
fn _subtract_balance(account: AztecAddress, amount: u128, max_notes: u32) -> u128 {
let subtracted = self.storage.private_balances.at(account).try_sub(amount, max_notes);
if subtracted >= amount {
subtracted - amount
} else {
assert(subtracted > 0, "Balance too low");
let remaining = amount - subtracted;
self.call_self.recurse_subtract_balance_internal(account, remaining)
}
}
```
The recursion terminates when either the full amount has been deducted or the assertion fires.
Without recursion, you would have to either size every circuit for the worst-case note count (making the common case expensive to prove) or fail transfers when the note count exceeds a fixed limit. Recursion gives the best of both worlds: the common case (2 notes) proves fast, while larger balances are handled by chaining multiple smaller proofs. Each recursive call is a separate private kernel circuit, so proving cost scales with the actual note count rather than the worst case.
---
# AIP-4626: Tokenized Vault
[Source](https://github.com/defi-wonderland/aztec-standards/tree/dev/src/vault_contract) (extends the AIP-20 token contract)
AIP-4626 extends [AIP-20](/developers/testnet/docs/aztec-nr/standards/aip-20.md) to describe a tokenized vault: a contract that holds an underlying asset and issues shares representing a proportional claim on that asset. It mirrors the design of ERC-4626 but adapts the share conversion arithmetic for Aztec's `u128` integer type.
## Share conversion[](#share-conversion "Direct link to Share conversion")
The vault tracks the total supply of shares and a `vault_offset` that prevents inflation attacks on the initial deposit. The conversion functions use integer arithmetic with configurable rounding direction:
```
#[internal("public")]
fn _convert_to_shares(assets: u128, total_assets: u128, rounding: bool) -> u128 {
let mul_term =
assets * (self.storage.total_supply.read() + self.storage.vault_offset.read());
let denominator = (total_assets + 1);
let mut shares = mul_term / denominator;
if (rounding == ROUND_UP) & (mul_term % denominator > 0) {
shares = shares + 1;
}
shares
}
#[internal("public")]
fn _convert_to_assets(shares: u128, total_assets: u128, rounding: bool) -> u128 {
let mul_term = shares * (total_assets + 1);
let denominator = (self.storage.total_supply.read() + self.storage.vault_offset.read());
let mut assets = mul_term / denominator;
if (rounding == ROUND_UP) & (mul_term % denominator > 0) {
assets = assets + 1;
}
assets
}
```
The `+ 1` in the denominator and the `vault_offset` together implement the "virtual shares" technique that prevents the first depositor from manipulating the exchange rate for subsequent depositors. Without this protection, an attacker could deposit 1 wei, then donate a large amount of the underlying asset directly to the vault, inflating the share price so that the next depositor's deposit rounds down to zero shares.
Deposits round shares down (in favor of the vault), while redemptions round assets down (also in favor of the vault). This is consistent with ERC-4626 rounding conventions and prevents rounding-based extraction attacks.
## Deposit flow[](#deposit-flow "Direct link to Deposit flow")
A public-to-public deposit transfers assets from the caller to the vault, computes the shares due, and mints them to the recipient:
```
#[external("public")]
fn deposit_public_to_public(from: AztecAddress, to: AztecAddress, assets: u128, _nonce: Field) {
self.internal._validate_from_public(from);
let total_assets = self.internal._total_assets();
let shares = self.internal._convert_to_shares(assets, total_assets, ROUND_DOWN);
// Transfer assets from sender to vault
self.call(Token::at(self.storage.asset.read()).transfer_public_to_public(
from, self.address, assets, _nonce,
));
// Mint shares to the recipient
self.internal._mint_to_public(to, shares);
}
```
The vault exposes similar entry points for the other combinations of private and public contexts (`deposit_private_to_public`, `deposit_public_to_private`, `deposit_private_to_private`). Each variant transfers assets using the corresponding AIP-20 transfer function and then mints shares into the chosen output context.
---
# AIP-721: Non-Fungible Token
[Source](https://github.com/defi-wonderland/aztec-standards/tree/dev/src/nft_contract)
AIP-721 defines a non-fungible token (NFT). Each token is identified by a unique `token_id` field. Tokens can be held privately in the note hash tree or publicly in a map from `token_id` to owner address.
## Storage layout[](#storage-layout "Direct link to Storage layout")
```
#[storage]
struct Storage<Context> {
symbol: PublicImmutable<FieldCompressedString, Context>,
name: PublicImmutable<FieldCompressedString, Context>,
private_nfts: Owned<PrivateSet<NFTNote, Context>, Context>,
nft_exists: Map<Field, PublicMutable<bool, Context>, Context>,
public_owners: Map<Field, PublicMutable<AztecAddress, Context>, Context>,
minter: PublicImmutable<AztecAddress, Context>,
upgrade_authority: PublicImmutable<AztecAddress, Context>,
}
```
`nft_exists` tracks whether a given `token_id` has been minted, while `public_owners` records the current public owner. When an NFT is moved to a private note, the `public_owners` entry is cleared and the NFT is stored as an `NFTNote` in the holder's private set.
## NFTNote and partial-note support[](#nftnote-and-partial-note-support "Direct link to NFTNote and partial-note support")
Each private NFT is represented as an `NFTNote` containing only the `token_id`:
```
#[derive(Eq, Serialize, Packable)]
#[custom_note]
pub struct NFTNote {
pub token_id: Field,
}
impl NFTNote {
pub fn partial(
owner: AztecAddress,
storage_slot: Field,
context: &mut PrivateContext,
recipient: AztecAddress,
completer: AztecAddress,
) -> PartialNFTNote {
let randomness = unsafe { random() };
let commitment = compute_partial_commitment(owner, storage_slot, randomness);
// ... creates encrypted log and validity commitment
let partial_note = PartialNFTNote { commitment };
let validity_commitment = partial_note.compute_validity_commitment(completer);
context.push_nullifier_unsafe(validity_commitment);
partial_note
}
}
```
The `partial` constructor creates a `PartialNFTNote` whose `commitment` field commits to the future owner and storage slot. Without some form of access control, any party could call the completion function and claim the NFT for themselves. The validity commitment prevents this — it is pushed as a nullifier, and only the designated completer can produce the matching preimage needed to finalize the note. This mirrors the partial-note pattern in [AIP-20](/developers/testnet/docs/aztec-nr/standards/aip-20.md) but applies it to NFT transfers.
## Partial-note transfer commitment[](#partial-note-transfer-commitment "Direct link to Partial-note transfer commitment")
The external entry point for initiating a partial NFT transfer is:
```
#[external("private")]
fn initialize_transfer_commitment(to: Azte프로젝트로 돌아가기