Aztec 백서

Aztec

원문

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

s can only be called from public external or internal functions ## Next steps[​](#next-steps "Direct link to Next steps") * [Attributes and Macros](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md) * [Call Types](/developers/testnet/docs/foundational-topics/call_types.md) --- # Visibility In Aztec there are multiple different types of visibility that can be applied to functions. Namely we have `data visibility` and `function visibility`. This page explains these types of visibility. ## Data visibility[​](#data-visibility "Direct link to Data visibility") Data visibility describes whether the data (or state) used in a function is generally accessible (public) or on a need-to-know basis (private). ## Function visibility[​](#function-visibility "Direct link to Function visibility") Function visibility describes whether a function is callable from other contracts, or only from within the same contract. This is similar to the visibility modifiers you may be familiar with from Solidity. ### The `#[external(...)]` attribute[​](#the-external-attribute "Direct link to the-external-attribute") In Aztec.nr, the `#[external(...)]` attribute marks a function as externally callable - meaning it can be invoked via a transaction or by other contracts. The attribute takes a parameter specifying the execution context: * `#[external("private")]` - The function executes in a private context with access to private state * `#[external("public")]` - The function executes in a public context with access to public state ### The `#[only_self]` attribute[​](#the-only_self-attribute "Direct link to the-only_self-attribute") By default, all external functions are callable from other contracts, similar to Solidity's `public` visibility. To restrict a function so it can only be called by the same contract, use the `#[only_self]` attribute: ``` #[external("public")] #[only_self] fn _increase_public_balance(to: AztecAddress, amount: u128) { // This function can only be called by this contract let new_balance = self.storage.public_balances.at(to).read().add(amount); self.storage.public_balances.at(to).write(new_balance); } ``` A common use case for `#[only_self]` is when a private function needs to modify public state. Since private functions cannot directly modify public state, they enqueue calls to public functions. By marking the public function with `#[only_self]`, you ensure that only your contract can call it - preventing external parties from manipulating the public state directly. danger Note that functions without `#[only_self]` can be used directly as an entry-point, which currently means that the `msg_sender` would be `0`. For this reason, using address `0` as a burn address is not recommended. You can learn more about this in the [Accounts concept page](/developers/testnet/docs/foundational-topics/accounts/keys.md). ### The `#[internal]` attribute[​](#the-internal-attribute "Direct link to the-internal-attribute") The `#[internal]` attribute is different from `#[only_self]`. While `#[only_self]` restricts *who* can call a function (only the same contract, but still via an external call), `#[internal]` functions are **inlined** into the calling function. This is similar to how Solidity's `internal` functions use EVM's `JUMP` instruction rather than `CALL`. Internal functions: * Cannot be called externally (no transaction can invoke them directly) * Are inlined at compile time into the functions that call them * Have access to the calling function's context To understand how visibility works under the hood, check out the [Inner Workings page](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md). --- # Global Variables Similar to Solidity's global `block` variable, Aztec exposes contextual values within each function via the `context` object. Aztec has two execution environments—Private and Public—each with different available globals. ## Private Global Variables[​](#private-global-variables "Direct link to Private Global Variables") Private functions access transaction context via [`TxContext`](/aztec-nr-api/testnet/noir_aztec/protocol/abis/transaction/tx_context/struct.TxContext.html). The following fields are accessible via `context` methods: ### Chain Id[​](#chain-id "Direct link to Chain Id") The unique identifier for the Aztec network instance (not the Ethereum chain the rollup settles to). ``` self.context.chain_id(); ``` ### Version[​](#version "Direct link to Version") The Aztec protocol version number. The genesis block has version 1. ``` self.context.version(); ``` ### Gas Settings[​](#gas-settings "Direct link to Gas Settings") The gas limits, max fees per gas, and inclusion fee set by the user for the transaction. ``` self.context.gas_settings(); ``` ## Public Global Variables[​](#public-global-variables "Direct link to Public Global Variables") Public functions access block-level context via [`GlobalVariables`](/aztec-nr-api/testnet/noir_aztec/protocol/abis/global_variables/struct.GlobalVariables.html). note Not all fields in `GlobalVariables` are exposed via context methods. The `coinbase`, `fee_recipient`, and `slot_number` fields are used internally by the protocol. Public functions have access to `chain_id()` and `version()` (same syntax as private), plus the following block-level values: ### Timestamp[​](#timestamp "Direct link to Timestamp") The unix timestamp when the block is executed. Provided by the block proposer, so it may have slight variance. Always increases monotonically. ``` self.context.timestamp(); ``` ### Block Number[​](#block-number "Direct link to Block Number") The sequential block identifier. Genesis block is 1, incrementing by 1 for each subsequent block. ``` self.context.block_number(); ``` ### Gas Fees[​](#gas-fees "Direct link to Gas Fees") The current L2 and DA gas prices for the block. You can access gas-related information via: ``` self.context.l2_gas_left(); // Remaining L2 gas self.context.da_gas_left(); // Remaining DA gas self.context.min_fee_per_l2_gas(); // L2 gas price self.context.min_fee_per_da_gas(); // DA gas price self.context.transaction_fee(); // Final tx fee (only available in teardown phase) ``` Why do available globals differ between environments? Private functions execute on the user's device before the transaction is submitted, so they cannot know which block will include the transaction. Therefore, `timestamp` and `block_number` are unavailable in private context. Public functions execute on a sequencer who knows the current block's timestamp and number, making these values accessible. --- # Immutables via Salt Aztec contracts can commit immutable values directly into the contract's address by encoding them into the deployment salt, removing the need for a separate initialization transaction. ## Overview[​](#overview "Direct link to Overview") Rather than storing immutables in private storage (which requires an initializer function and an extra transaction), the [aztec-immutables-macro](https://github.com/defi-wonderland/aztec-immutables-macro/tree/dev) library encodes them into the contract's salt: ``` salt = poseidon2_hash([actual_salt, constant_0, constant_1, ...]) ``` Since the salt is part of the address derivation, the immutable values become cryptographically bound to the contract's address itself. ## Key benefits[​](#key-benefits "Direct link to Key benefits") * **No initialization transaction** — immutables are committed at deployment time, not in a separate setup call * **Runtime verification** — at execution time, capsule data is loaded and verified against the stored salt, ensuring data integrity * **Persistent storage** — immutables are persisted to the PXE's [CapsuleStore](/developers/testnet/docs/aztec-nr/framework-description/advanced/how_to_use_capsules.md) after deployment, so capsules don't need to be attached to every transaction * **Compatible with standard storage** — works alongside `#[storage]` and initializers when needed ## Performance[​](#performance "Direct link to Performance") Initialization cost is completely eliminated (no constructor transaction). The per-transaction overhead is approximately 1,098 gates (+0.2%) in the account entrypoint. ## Getting started[​](#getting-started "Direct link to Getting started") For installation instructions, usage examples, and a reference implementation of an initializerless Schnorr account contract, see the [aztec-immutables-macro README](https://github.com/defi-wonderland/aztec-immutables-macro/tree/dev). --- # Aztec Macros Aztec.nr provides macros (attributes) that transform your code during compilation to handle the complexities of private execution, proof generation, and state management. ## Quick reference[​](#quick-reference "Direct link to Quick reference") ### Contract[​](#contract "Direct link to Contract") | Attribute | Purpose | | ---------- | ----------------------------------- | | `#[aztec]` | Marks a module as an Aztec contract | ### Functions[​](#functions "Direct link to Functions") | Attribute | Purpose | | ------------------------ | ----------------------------------------------------------------- | | `#[external("private")]` | Client-side private execution with proofs | | `#[external("public")]` | Sequencer-side public execution | | `#[external("utility")]` | Unconstrained queries, not included in transactions | | `#[internal("private")]` | Private helper, only callable within the same contract | | `#[internal("public")]` | Public helper, only callable within the same contract | | `#[view]` | Prevents state modification | | `#[initializer]` | Contract constructor | | `#[noinitcheck]` | Callable before contract initialization | | `#[allow_phase_change]` | Allows for phase change to happen during the function's execution | | `#[only_self]` | Only callable by the same contract | | `#[authorize_once]` | Requires authwit authorization with replay protection | Functions can have multiple attributes (e.g., `#[external("public")]` with `#[view]` and `#[only_self]`). ### Structs[​](#structs "Direct link to Structs") | Attribute | Purpose | | -------------------- | ------------------------------------- | | `#[note]` | Defines a private note type | | `#[custom_note]` | Note with custom hash/nullifier logic | | `#[storage]` | Defines contract storage layout | | `#[storage_no_init]` | Storage with manual slot allocation | For detailed explanations and examples, see the [Attributes and Macros reference](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md). ## Further reading[​](#further-reading "Direct link to Further reading") * [Attributes and Macros reference](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md) - detailed documentation for each macro * [Inner workings of functions](/developers/testnet/docs/aztec-nr/framework-description/functions/function_transforms.md) - how macros transform your code --- # Note Delivery When you create a note in an Aztec smart contract, you must deliver it to the recipient so they can use it. This page explains how note delivery works and how to choose the right delivery mode for your use case. ## Overview[​](#overview "Direct link to Overview") In Aztec, creating a note involves two steps: 1. **Creating the note** - Adding the note hash to the note hash tree 2. **Delivering the note** - Sending the note contents to the recipient so they can decrypt and use it Without delivery, the recipient won't know the note exists or be able to access its contents, even though the note hash is onchain. ## The `.deliver()` method[​](#the-deliver-method "Direct link to the-deliver-method") When you create a note using state variables like `PrivateMutable`, `PrivateSet`, `BalanceSet`, or `SinglePrivateMutable`, the creation methods return a `NoteMessage` or `MaybeNoteMessage` object. A message contains arbitrary information emitted from a contract - currently this includes notes and private events, though developers may define other message types in the future. You must call `.deliver()` on this object to send the message (containing the note) to the recipient. ``` #[aztec] pub contract PrivateToken { use aztec::messages::delivery::MessageDelivery; #[external("private")] fn mint(amount: u128, recipient: AztecAddress) { // Adding to the balance returns a MaybeNoteMessage self.storage.balances.at(recipient).add(amount) .deliver(MessageDelivery::onchain_constrained()); } } ``` ## Delivery Modes[​](#delivery-modes "Direct link to Delivery Modes") Aztec provides three delivery modes that offer different tradeoffs between cost, proving time, and guarantees: ### `MessageDelivery::offchain()`[​](#messagedeliveryoffchain "Direct link to messagedeliveryoffchain") **Fully offchain delivery with no guarantees.** This delivery method encrypts messages without constraints and emits them via an oracle call as offchain effects, rather than through the protocol's log stream (which would post data to Ethereum blobs). With offchain delivery, you must manually handle both message transmission and processing. #### How it works[​](#how-it-works "Direct link to How it works") Offchain messages bypass Aztec's default private log infrastructure entirely: 1. **Message emission**: The contract encrypts the message (without constraints) and emits it via an oracle call. This creates an "offchain effect" that is included in the transaction but not posted to L1. 2. **Extraction**: When the transaction is sent, you read the emitted messages from the send result (`offchainMessages` in aztec.js), or extract them from a proven transaction's offchain effects. 3. **Manual delivery**: You deliver the message through your own channel - a claim link, QR code, messaging service, cloud storage, etc. 4. **Receipt and processing**: The recipient calls the `offchain_receive` utility function on the contract that emitted the message (this function is generated automatically by the `#[aztec]` macro). The message is stored in a local inbox and processed during private state sync once the transaction that emitted it is found onchain. The PXE cannot automatically discover offchain messages during private state sync because they are not in the log stream that nodes load from Ethereum blobs. **You are responsible for implementing the delivery mechanism and ensuring the recipient receives the message.** See [Offchain message delivery](/developers/testnet/docs/aztec-nr/framework-description/offchain_message_delivery.md) for the complete workflow, including sender and recipient code, message processing details, and how to test it from Noir. #### When to use[​](#when-to-use "Direct link to When to use") * **Use when:** The sender is incentivized to deliver correctly (e.g., sending to yourself, payment for goods/services where recipient must receive the note to complete the transaction) * **Costs:** Zero delivery fees (no blob space), zero proving time overhead * **Guarantees:** None. The sender can fail to deliver or deliver incorrect content * **Privacy:** Maximum. No onchain data is emitted This is expected to be the most common delivery method when you don't need constrained delivery guarantees, as it completely eliminates blob space costs. #### Example use cases[​](#example-use-cases "Direct link to Example use cases") * Change notes when transferring tokens (you're sending to yourself) * Payments where the recipient won't provide goods/services without the note * Messages to local accounts controlled by the sender * Low-value use-cases like delivering game state updates to a game server ``` // Change note - sender is motivated to deliver to themselves self.storage.balances.at(sender).add(change_amount) .deliver(MessageDelivery::offchain()); ``` #### JavaScript implementation[​](#javascript-implementation "Direct link to JavaScript implementation") When using offchain delivery, extract the emitted messages from the send result and deliver them to the recipient in your application. The recipient hands each message to their wallet via the auto-generated `offchain_receive` utility function: ``` // Sender: send the transaction and extract the emitted offchain messages const { receipt, offchainMessages } = await token.methods .transfer_in_private_with_offchain_delivery(alice, bob, amount, 0) .send({ from: alice }); const messageForBob = offchainMessages.find((msg) => msg.recipient.equals(bob)); // Deliver via your chosen channel (e.g. a claim link, QR code, messaging service). // This is what you'd have to implement. await deliverViaMyChannel(messageForBob, receipt.txHash, recipient); // Recipient: receive the message so it gets processed during sync await token.methods .offchain_receive([ { ciphertext: messageForBob.payload, recipient: bob, tx_hash: receipt.txHash.hash, anchor_block_timestamp: messageForBob.anchorBlockTimestamp, }, ]) .simulate({ from: bob }); ``` See [Offchain message delivery](/developers/testnet/docs/aztec-nr/framework-description/offchain_message_delivery.md) for the full workflow. ### `MessageDelivery::onchain_unconstrained()`[​](#messagedeliveryonchain_unconstrained "Direct link to messagedeliveryonchain_unconstrained") **Onchain delivery with no content guarantees.** This mode provides the same low proving time as offchain delivery while avoiding the need to implement custom delivery infrastructure. The tradeoff: you pay for DA (blob space) without gaining additional guarantees. If you're willing to build offchain delivery, use it instead - it's strictly cheaper with the same guarantees. * **Use when:** The sender is incentivized to deliver correctly but you don't want to implement offchain delivery infrastructure * **Costs:** DA gas fees for the encrypted log, zero proving time overhead * **Guarantees:** Message stored onchain and retrievable, but sender can deliver incorrect content or wrong tag * **Privacy:** High for the message contents. By default, reaching a recipient the sender has not handshaked with before establishes a handshake that reveals the recipient was contacted (see [Tagging secret strategy](#tagging-secret-strategy)) ``` // Minting to an admin who controls the contract self.storage.balances.at(admin).add(amount) .deliver(MessageDelivery::onchain_unconstrained()); ``` ### `MessageDelivery::onchain_constrained()`[​](#messagedeliveryonchain_constrained "Direct link to messagedeliveryonchain_constrained") **Onchain delivery with guaranteed correct content.** * **Use when:** The sender cannot be trusted to deliver correctly (e.g., paying fees, creating notes for others, multisig configuration changes). Use this when you need to prove to a contract that the delivery has been done correctly. You can imagine a private NFT sale escrow contract where the escrow would be holding the NFT (the contract itself would be the NFT note owner) and then the escrow would release the NFT to the buyer once the NFT buyer pays the seller. In this case the `NFTSale::buy(...)` function would trigger the payment token transfer from the buyer to the seller and it would need to use constrained delivery otherwise the escrow contract would be willing to transfer the NFT without the NFT seller actually being able to then spend the money. Note that for the transfer of the NFT from the escrow contract to the buyer you could use offchain delivery because the delivery and encryption would be done in the buyer's PXE and hence there is alignment. * **Costs:** DA gas fees for the encrypted log, proving time overhead for encryption and tagging * **Guarantees:** Recipient will always be able to find correctly encrypted content: both the encryption and the discovery tag are constrained and stored onchain. * **Privacy:** High for the message contents. By default, reaching a recipient the sender has not handshaked with before establishes
프로젝트로 돌아가기