Aztec 백서

Aztec

원문

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

type for storing `u128` values. Also includes `PartialUintNote` for partial note workflows where the value is completed in public execution. ## State Variables[​](#state-variables "Direct link to State Variables") ### Balance Set[​](#balance-set "Direct link to Balance Set") ``` balance_set = { git="https://github.com/aztec-labs-eng/aztec-nr/", tag="v6.0.0-rc.1", directory="balance-set" } ``` Provides `BalanceSet`, a state variable for managing private balances. Includes helper functions for adding, subtracting, and querying balances. ## Utilities[​](#utilities "Direct link to Utilities") ### Compressed String[​](#compressed-string "Direct link to Compressed String") ``` compressed_string = { git="https://github.com/aztec-labs-eng/aztec-nr/", tag="v6.0.0-rc.1", directory="compressed-string" } ``` Provides `CompressedString` and `FieldCompressedString` utilities for working with compressed string data. ## Updating your aztec dependencies[​](#updating-your-aztec-dependencies "Direct link to Updating your aztec dependencies") When `aztec compile` warns that your aztec dependency tag does not match the CLI version, update the `tag` field in every Aztec.nr entry in your `Nargo.toml` to match the CLI version you are running. For example, if your CLI is `v6.0.0-rc.1`, change: ``` aztec = { git="https://github.com/aztec-labs-eng/aztec-nr/", tag="v<old-version>", directory="aztec" } ``` to: ``` aztec = { git="https://github.com/aztec-labs-eng/aztec-nr/", tag="v6.0.0-rc.1", directory="aztec" } ``` Repeat for every other Aztec.nr dependency in your `Nargo.toml` (e.g. `address_note`, `balance_set`, etc.). You can check your current CLI version with `aztec --version`. --- # Ethereum<>Aztec Messaging This guide covers cross-chain communication between Ethereum (L1) and Aztec (L2) using portal contracts. Aztec uses an Inbox/Outbox pattern for cross-chain messaging. Messages sent from L1 are inserted into the `Inbox` contract and later consumed on L2. Messages sent from L2 are inserted into the `Outbox` contract and later consumed on L1. Portal contracts are L1 contracts that facilitate this communication for your application. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * An Aztec contract project with `aztec-nr` dependency * Access to Ethereum development environment for L1 contracts * Deployed portal contract on L1 (see [token bridge tutorial](/developers/testnet/docs/tutorials/js_tutorials/token_bridge.md)) ## L1 to L2 messaging[​](#l1-to-l2-messaging "Direct link to L1 to L2 messaging") ### Send a message from L1[​](#send-a-message-from-l1 "Direct link to Send a message from L1") Use the `Inbox` contract's `sendL2Message` function: | Parameter | Type | Description | | ------------- | --------- | -------------------------------------------------- | | `_recipient` | `L2Actor` | L2 contract address and rollup version | | `_content` | `bytes32` | Hash of message content (use `Hash.sha256ToField`) | | `_secretHash` | `bytes32` | Hash of secret for message consumption | deposit\_to\_aztec\_public ``` /// @notice Deposit tokens and send L1->L2 message for public minting on Aztec function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) external returns (bytes32, uint256) { DataStructures.L2Actor memory actor = DataStructures.L2Actor(l2Bridge, rollupVersion); bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("mint_to_public(bytes32,uint256)", _to, _amount)); underlying.safeTransferFrom(msg.sender, address(this), _amount); return inbox.sendL2Message(actor, contentHash, _secretHash); } ``` > [Source code: docs/examples/solidity/example\_swap/ExampleTokenPortal.sol#L43-L59](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/solidity/example_swap/ExampleTokenPortal.sol#L43-L59) Message availability L1 to L2 messages are not available immediately. The proposer batches messages from the Inbox and includes them in the next L2 block. You must wait for this before consuming the message on L2. ### Consume the message on L2[​](#consume-the-message-on-l2 "Direct link to Consume the message on L2") Call `consume_l1_to_l2_message` on the context. The `content` must match the hash sent from L1, and the `secret` must be the pre-image of the `secretHash`. Consuming a message emits a nullifier to prevent double-spending. The content hash must be computed identically on both L1 and L2. Create a shared library for your content hash functions—see [`token_portal_content_hash_lib`](https://github.com/aztec-labs-eng/aztec-node/tree/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/libs/token_portal_content_hash_lib) for an example. claim\_public ``` // Consumes a L1->L2 message and calls the token contract to mint the appropriate amount publicly #[external("public")] fn claim_public(to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field) { let content_hash = get_mint_to_public_content_hash(to, amount); let config = self.storage.config.read(); // Consume message and emit nullifier self.context.consume_l1_to_l2_message(content_hash, [secret], config.portal, message_leaf_index); // Mint tokens self.call(Token::at(config.token).mint_to_public(to, amount)); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_bridge\_contract/src/main.nr#L63-L77](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L63-L77) This function works in both public and private contexts. ## L2 to L1 messaging[​](#l2-to-l1-messaging "Direct link to L2 to L1 messaging") ### Send a message from L2[​](#send-a-message-from-l2 "Direct link to Send a message from L2") Call `message_portal` on the context to send messages to your L1 portal: exit\_to\_l1\_public ``` // Burns the appropriate amount of tokens and creates a L2 to L1 withdraw message publicly // Requires `msg.sender` to give approval to the bridge to burn tokens on their behalf using witness signatures #[external("public")] fn exit_to_l1_public( recipient: EthAddress, // ethereum address to withdraw to amount: u128, caller_on_l1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can // call) authwit_nonce: Field, // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on // L2 ) { let config = self.storage.config.read(); // Send an L2 to L1 message let content = get_withdraw_content_hash(recipient, amount, caller_on_l1); self.context.message_portal(config.portal, content); // Burn tokens self.call(Token::at(config.token).burn_public(self.msg_sender(), amount, authwit_nonce)); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_bridge\_contract/src/main.nr#L79-L100](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L79-L100) This function works in both public and private contexts. ### Consume the message on L1[​](#consume-the-message-on-l1 "Direct link to Consume the message on L1") Use the `Outbox` contract to consume L2 messages. Message availability L2 to L1 messages are only available after the epoch proof is submitted to L1. Since multiple L2 blocks fit within an epoch, there may be a delay—especially if the message was sent near the start of an epoch. withdraw ``` /// @notice Withdraw tokens after consuming an L2->L1 message. /// @param _numCheckpointsInEpoch The partial-proof depth (1-indexed) the witness was built against. function withdraw( address _recipient, uint256 _amount, Epoch _epoch, uint256 _numCheckpointsInEpoch, uint256 _leafIndex, bytes32[] calldata _path ) external { DataStructures.L2ToL1Msg memory message = DataStructures.L2ToL1Msg({ sender: DataStructures.L2Actor(l2Bridge, rollupVersion), recipient: DataStructures.L1Actor(address(this), block.chainid), content: Hash.sha256ToField( abi.encodeWithSignature("withdraw(address,uint256,address)", _recipient, _amount, msg.sender) ) }); outbox.consume(message, _epoch, _numCheckpointsInEpoch, _leafIndex, _path); underlying.safeTransfer(_recipient, _amount); } ``` > [Source code: docs/examples/solidity/example\_swap/ExampleTokenPortal.sol#L72-L95](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/solidity/example_swap/ExampleTokenPortal.sol#L72-L95) Getting the membership witness Compute the witness for the L2 to L1 message in TypeScript: ``` import { computeL2ToL1MessageHash } from "@aztec-labs/stdlib/hash"; const l2ToL1Message = computeL2ToL1MessageHash({ l2Sender: l2BridgeAddress, l1Recipient: EthAddress.fromString(portalAddress), content: withdrawContentHash, rollupVersion: new Fr(version), chainId: new Fr(chainId), }); const witness = await aztecNode.getL2ToL1MembershipWitness( txReceipt.txHash, l2ToL1Message ); // Use witness.leafIndex and witness.siblingPath for the L1 consume call ``` ## Example implementations[​](#example-implementations "Direct link to Example implementations") * [Token Portal (L1)](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/solidity/example_swap/ExampleTokenPortal.sol) * [Token Bridge (L2)](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr) ## Next steps[​](#next-steps "Direct link to Next steps") Follow the [token bridge tutorial](/developers/testnet/docs/tutorials/js_tutorials/token_bridge.md) for a complete implementation example. --- # Events and Logs Events allow contracts to communicate with offchain applications. Private events are encrypted and delivered to specific recipients, while public events are visible to everyone. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * An Aztec contract project set up with `aztec-nr` dependency * Understanding of private vs public functions in Aztec ## Define an event[​](#define-an-event "Direct link to Define an event") Declare events using the `#[event]` attribute: ``` #[event] struct Transfer { from: AztecAddress, to: AztecAddress, amount: u128, } ``` ## Emit private events[​](#emit-private-events "Direct link to Emit private events") In private functions, emit events using `self.emit()` and deliver them to recipients: ``` use aztec::messages::delivery::MessageDelivery; #[external("private")] fn transfer(to: AztecAddress, amount: u128) { let from = self.msg_sender(); // ... transfer logic ... self.emit(Transfer { from, to, amount }).deliver_to( to, MessageDelivery::onchain_unconstrained(), ); } ``` warning You **must** call `deliver_to()` on the returned `EventMessage`. If you don't, the event information is lost forever. The compiler will warn you about unused `EventMessage` values. ### Deliver to multiple recipients[​](#deliver-to-multiple-recipients "Direct link to Deliver to multiple recipients") You can deliver the same event to multiple recipients with different delivery modes: ``` let message = self.emit(Transfer { from, to, amount }); message.deliver_to(from, MessageDelivery::offchain()); message.deliver_to(to, MessageDelivery::onchain_constrained()); ``` The `MessageDelivery` options are: * **`onchain_constrained()`** - Constrained encryption with onchain delivery. Slowest proving but provides cryptographic guarantees that recipients can decrypt messages. * **`onchain_unconstrained()`** - Unconstrained encryption with onchain delivery. Faster proving, but trusts the sender to encrypt correctly. * **`offchain()`** - Unconstrained encryption with offchain delivery. Lowest cost, but requires custom infrastructure to deliver messages to recipients. note Emitting private events is optional. Onchain delivery publishes encrypted data to Ethereum blobs, inheriting Ethereum's data availability guarantees. You can choose to share information offchain instead. ## Emit public events[​](#emit-public-events "Direct link to Emit public events") In public functions, emit events using `self.emit()`: ``` #[external("public")] fn update_value(value: Field) { // ... update logic ... self.emit(ValueUpdated { value }); } ``` Public events are emitted as plaintext logs, similar to Solidity events. ## Emit unstructured public logs[​](#emit-unstructured-public-logs "Direct link to Emit unstructured public logs") For unstructured data, use `emit_public_log_unsafe` directly on the context. It takes a tag (placed at the first field of the emitted log, which nodes use to index logs) followed by the data: ``` self.context.emit_public_log_unsafe(0, "My message"); self.context.emit_public_log_unsafe(0, [1, 2, 3]); ``` The tag should be domain-separated to prevent collisions with unrelated log types. Prefer `self.emit(event)` where possible, which handles tagging automatically. ## Query public logs[​](#query-public-logs "Direct link to Query public logs") Query public logs from offchain applications using the Aztec node. Raw public logs are attached to each block's transaction effects — fetch a block with `includeTransactions: true` and read `body.txEffects[*].publicLogs`: ``` const blockNumber = await node.getBlockNumber(); const block = await node.getBlock(blockNumber, { includeTransactions: true }); const publicLogs = block?.body.txEffects.flatMap(tx => tx.publicLogs) ?? []; ``` ## Cost considerations[​](#cost-considerations "Direct link to Cost considerations") Event data published onchain is stored in Ethereum blobs, which incurs costs. Consider: * Use offchain delivery for lower costs when you have custom delivery infrastructure * Only emit events when necessary for your application's functionality ## Next steps[​](#next-steps "Direct link to Next steps") * Learn about [storage](/developers/testnet/docs/aztec-nr/framework-description/state_variables.md) to persist data in your contracts * Explore [calling other contracts](/developers/testnet/docs/aztec-nr/framework-description/calling_contracts.md) for cross-contract interactions * Understand [cross-chain communication](/developers/testnet/docs/aztec-nr/framework-description/ethereum_aztec_messaging.md) between Ethereum and Aztec --- # Defining Functions Functions serve as the building blocks of smart contracts. Functions can be either **public**, ie they are publicly available for anyone to see and can directly interact with public state, or **private**, meaning they are executed completely client-side in the [PXE](/developers/testnet/docs/foundational-topics/pxe.md). Read more about how private functions work [here](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md#private-functions-externalprivate). Currently, any function is "mutable" in the sense that it might alter state. However, we also support static calls, similarly to EVM. A static call is essentially a call that does not alter state (it keeps state static). ## Initializer functions[​](#initializer-functions "Direct link to Initializer functions") Smart contracts may have one, or many, initializer functions which are called when the contract is deployed. Initializers are regular functions that set an "initialized" flag (a nullifier) for the contract. A contract can only be initialized once, and contract functions can only be called after the contract has been initialized, much like a constructor. However, if a contract defines no initializers, it can be called at any time. Additionally, you can define as many initializer functions in a contract as you want, both private and public. ## Oracles[​](#oracles "Direct link to Oracles") There are also special oracle functions, which can get data from outside of the smart contract. In the context of Aztec, oracles are often used to get user-provided inputs. ## Learn more about functions[​](#learn-more-about-functions "Direct link to Learn more about functions") * [How function visibility works in Aztec](/developers/testnet/docs/aztec-nr/framework-description/functions/visibility.md) * How to write an [initializer function](/developers/testnet/docs/aztec-nr/framework-description/functions/how_to_define_functions.md#define-initializer-functions) * [Oracles](/developers/testnet/docs/aztec-nr/framework-description/advanced/protocol_oracles.md) and how Aztec smart contracts might use them * [How functions work under the hood](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md) Find a function macros reference [here](/developers/testnet/docs/aztec-nr/framework-description/macros.md) --- # Attributes and Macros This page documents the attributes (macros) available in Aztec.nr for defining contract functions, storage, and notes. ## Quick reference[​](#quick-reference "Direct link to Quick reference") | Attribute | Applies to | Purpose | | ------------------------ | ---------- | ----------------------------------------------------------------- | | `#[external("private")]` | functions | Client-side private execution with proofs | | `#[external("public")]` | functions | Sequencer-side public execution | | `#[external("utility")]` | functions | Unconstrained queries, not included in transactions | | `#[internal("private")]` | functions | Private helper functions, inlined at call sites | | `#[internal("public")]` | functions | Public helper functions, inlined at call sites | | `#[view]` | functions | Prevents state modification | | `#[initializer]` | functions | Contract constructor | | `#[noinitcheck]` | functions | Callable before contract initialization | | `#[allow_phase_change]` | functions | Allows for phase change to happen during the function's execution | | `#[only_self]` | functions | Only callable by the same contract | | `#[authorize_once]` | functions | Requires authwit authorization with replay protection | | `#[note]` | structs | Defines a private note type | | `#[custom_note]` | structs | Defines a note with custom hash/nullifier logic | | `#[storage]` | structs | Defines contract storage layout | | `#[storage_no_init]` | structs | Storage with manual slot allocation | For macro internals, see the [macros reference](/developers/testnet/docs/aztec-nr/framework-description/macros.md). # External functions #\[external("...")] Like in Solidity, external functions can be called from outside the contract. There are 3 types of external functions differing in the execution environment they are executed in: private, public, and utility. We will describe each type in the following sections. ## Private functions #\[external("private")][​](#private-functions-externalprivate "Direct link to Private functions #\[external(\"private\")]") A private function operates on private information, and is executed by the user on their device. Annotate the function with the `#[external("private")]` attribute to tell the compiler it's a private function. This will make the [private context](/developers/testnet/docs/aztec-nr/framework-description/functions/context.md#the-private-context) available within the function's execution scope. The compiler will create a circuit to define this function. `#[external("private")]` is just syntactic sugar. At compile time, the Aztec.nr framework inserts code that allows the function to interact with the [kernel](/developers/testnet/docs/foundational-topics/advanced/circuits/private_kernel.md). If you are interested in what exactly the macros are doing we encourage you to run `aztec-nargo expand` on your contract. This will display your contract's code after the transformations are performed. (If you are using VSCode you can display the expanded code by pressing `CMD + Shift + P` and typing `nargo expand` and selecting `Noir: nargo expand on current package`. Make sure the Noir extension's `Nargo Path` is set to `aztec-nargo` — see the [Noir VSCode extension guide](/developers/testn
프로젝트로 돌아가기