Aztec 백서

Aztec

원문

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

).mint_to_public(recipient, amount)); } } ``` warning Do not import generated interfaces from the same project as the source contract to avoid circular references. ## Next steps[​](#next-steps "Direct link to Next steps") After compilation, use the generated artifacts to: * Deploy contracts with the `Contract` class from `aztec.js` * Interact with deployed contracts using type-safe interfaces * Import contracts in other Aztec.nr projects --- # Contract Deployment Reference This guide helps you quickly determine which deployment steps your contract needs. For conceptual background on how contract deployment works, see [Contract Deployment](/developers/testnet/docs/foundational-topics/contract_creation.md). ## What Do I Need to Do?[​](#what-do-i-need-to-do "Direct link to What Do I Need to Do?") Use this decision tree to determine which steps your contract needs. <!-- --> No initializer? If your contract has no `#[initializer]` function and was deployed with `without_initializer()`, it's considered initialized immediately. Skip the initialization checks above. ## Checking Contract State Programmatically[​](#checking-contract-state-programmatically "Direct link to Checking Contract State Programmatically") Use `wallet.getContractMetadata(contractAddress)` to check whether a contract is registered, published, and initialized. See [Verify deployment](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md#verify-deployment) for usage examples and details on what the PXE checks automatically versus what you need to verify manually. ## When Can You Skip States?[​](#when-can-you-skip-states "Direct link to When Can You Skip States?") | Contract Type | Class Registration | Instance Creation | Initialization | Public Deployment | | ------------------------- | ------------------ | ----------------- | -------------- | ----------------- | | Private-only | Optional | Required | Depends | Skip | | Public-only | Required | Required | Depends | Required | | Hybrid (private + public) | Required | Required | Depends | Required | | Stateless helper | Optional | Required | Skip | Depends | "Depends" means it depends on whether your contract has a constructor marked with `#[initializer]`. ## When Functions Become Callable[​](#when-functions-become-callable "Direct link to When Functions Become Callable") | State | Private Functions | Public Functions | | ----------------------------------- | --------------------- | ---------------- | | Address computed only | With `#[noinitcheck]` | No | | Class registered | With `#[noinitcheck]` | No | | Instance deployed (not initialized) | With `#[noinitcheck]` | No | | Initialized | Yes | No | | Publicly deployed | Yes | Yes | Private functions marked with `#[noinitcheck]` can be called as soon as you know the address, even before initialization. This enables patterns like pre-funded accounts. Contracts without initializers If your contract has no initializer and is deployed with `without_initializer()`, it's considered initialized immediately. Private functions are callable right after instance creation without needing `#[noinitcheck]`. Public functions still require public deployment. ## Further Reading[​](#further-reading "Direct link to Further Reading") * [Contract Deployment](/developers/testnet/docs/foundational-topics/contract_creation.md) - Conceptual foundation of classes, instances, and lifecycle states * [Deploying Contracts](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md) - TypeScript deployment guide * [Defining Initializer Functions](/developers/testnet/docs/aztec-nr/framework-description/functions/how_to_define_functions.md#define-initializer-functions) - How to use `#[initializer]` and `#[noinitcheck]` * [Communicating Cross-Chain](/developers/testnet/docs/aztec-nr/framework-description/ethereum_aztec_messaging.md) - Portal contracts and L1/L2 messaging --- # Debugging Aztec Code This guide shows you how to debug issues in your Aztec development environment. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * Running Aztec local network * Aztec.nr contract or aztec.js application * Basic understanding of Aztec architecture ## Enable logging[​](#enable-logging "Direct link to Enable logging") For adding log statements to your contracts, controlling log verbosity, and understanding the `LOG_LEVEL` syntax, see the [Logging from Contracts](/developers/testnet/docs/aztec-nr/logging.md) guide. To enable verbose system-level logging on a local network: ``` LOG_LEVEL=verbose aztec start --local-network ``` ## Debugging common errors[​](#debugging-common-errors "Direct link to Debugging common errors") ### Contract Errors[​](#contract-errors "Direct link to Contract Errors") | Error | Solution | | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Aztec dependency not found` | Add to Nargo.toml: `aztec = { git="https://github.com/aztec-labs-eng/aztec-node/", tag="v6.0.0-rc.1", directory="noir-projects/aztec-nr/aztec" }` | | `Public state writes only supported in public functions` | Move state writes to public functions | | `Unknown contract 0x0` | Call `wallet.registerContract(...)` to register contract | | `No public key registered for address` | Call `wallet.registerSender(...)` | | `Direct invocation of ... functions is not supported` | Use `self.call()`, `self.view()`, or `self.enqueue()` to [call contract functions](/developers/testnet/docs/aztec-nr/framework-description/calling_contracts.md) | | `Failed to solve brillig function` | Check function parameters and note validity | | `Cross-contract utility call denied` | Configure an `authorizeUtilityCall` [execution hook](#cross-contract-utility-call-denied) on your PXE | #### Cross-contract utility call denied[​](#cross-contract-utility-call-denied "Direct link to Cross-contract utility call denied") Utility functions execute on the user's device and have access to private state. A cross-contract utility call made by a malicious or compromised contract could leak private information to an untrusted contract. PXE therefore denies cross- contract utility calls by default and requires explicit authorization via an execution hook. Calls to standard contracts (such as the HandshakeRegistry, which is queried during every contract's sync) are always automatically authorized. When a contract executes a utility function that calls into a different contract, PXE asks the wallet through an [execution hook](/developers/testnet/docs/foundational-topics/pxe/execution_hooks.md) whether the call should be allowed. If no hook is configured, or the wallet denies the request, you will see: ``` Cross-contract utility call denied: <reason>. <caller> attempted to call <target>:<selector> (<name>). ``` See [execution hooks](/developers/testnet/docs/foundational-topics/pxe/execution_hooks.md#authorizeutilitycall) for how to authorize calls, both in production and in Noir tests. ### Circuit Errors[​](#circuit-errors "Direct link to Circuit Errors") | Error Code | Meaning | Fix | | ----------- | ---------------------------- | -------------------------------------------------- | | `2002` | Invalid contract address | Ensure contract is deployed and address is correct | | `2005/2006` | Static call violations | Remove state modifications from static calls | | `2017` | User intent mismatch | Verify transaction parameters match function call | | `3001` | Unsupported operation | Check if operation is supported in current context | | `3005` | Non-empty private call stack | Ensure private functions complete before public | | `4007/4008` | Chain ID/version mismatch | Verify L1 chain ID and Aztec version | | `7008` | Membership check failed | Ensure using valid historical state | | `7009` | Array overflow | Reduce number of operations in transaction | ### Quick Fixes for Common Issues[​](#quick-fixes-for-common-issues "Direct link to Quick Fixes for Common Issues") ``` # Archiver sync issues - force progress with dummy transactions. # Assumes you have imported the local network test accounts # (aztec-wallet import-test-accounts) and have a deployed token # aliased as `testtoken`. aztec-wallet send transfer --from test0 --contract-address testtoken --args accounts:test0 0 aztec-wallet send transfer --from test0 --contract-address testtoken --args accounts:test0 0 # L1 to L2 message pending - wait for inclusion # Messages need 2 blocks to be processed ``` ## Debugging WASM errors[​](#debugging-wasm-errors "Direct link to Debugging WASM errors") ### Enable debug WASM[​](#enable-debug-wasm "Direct link to Enable debug WASM") ``` // In vite.config.ts or similar export default { define: { "process.env.BB_WASM_PATH": JSON.stringify("https://debug.wasm.url"), }, }; ``` ### Profile transactions[​](#profile-transactions "Direct link to Profile transactions") ``` import { serializePrivateExecutionSteps } from "@aztec-labs/stdlib"; // Profile the transaction const profileTx = await contract.methods .myMethod(param1, param2) .profile({ profileMode: "execution-steps" }); // Serialize for debugging const ivcMessagePack = serializePrivateExecutionSteps(profileTx.executionSteps); // Download debug file const blob = new Blob([ivcMessagePack]); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = "debug-steps.msgpack"; link.click(); ``` ⚠️ **Warning:** Debug files may contain private data. Use only in development. ## Interpret error messages[​](#interpret-error-messages "Direct link to Interpret error messages") ### Circuit and protocol errors[​](#circuit-and-protocol-errors "Direct link to Circuit and protocol errors") * **Private kernel errors (2xxx)**: Issues with private function execution * **Public kernel errors (3xxx)**: Issues with public function execution * **Rollup errors (4xxx)**: Block production issues * **Generic errors (7xxx)**: Resource limits or state validation ### Transaction limits[​](#transaction-limits "Direct link to Transaction limits") Current limits that trigger `7009 - ARRAY_OVERFLOW`: * Max new notes per tx: Check `MAX_NOTE_HASHES_PER_TX` * Max nullifiers per tx: Check `MAX_NULLIFIERS_PER_TX` * Max function calls: Check call stack size limits * Max L2→L1 messages: Check message limits ## Debugging sequencer issues[​](#debugging-sequencer-issues "Direct link to Debugging sequencer issues") ### Common sequencer errors[​](#common-sequencer-errors "Direct link to Common sequencer errors") | Error | Cause | Solution | | ------------------------------------ | --------------------- | ------------------------------------------------ | | `tree root mismatch` | State inconsistency | Restart local network or check state transitions | | `next available leaf index mismatch` | Tree corruption | Verify tree updates are sequential | | `Public call stack size exceeded` | Too many public calls | Reduce public function calls | | `Failed to publish block` | L1 submission failed | Check L1 connection and gas | ## Reporting issues[​](#reporting-issues "Direct link to Reporting issues") When debugging fails: 1. Collect error messages and codes 2. Generate transaction profile (if applicable) 3. Note your environment setup 4. Create issue at [aztec-packages](https://github.com/AztecProtocol/aztec-packages/issues/new) ## Quick reference[​](#quick-reference "Direct link to Quick reference") ### Enable verbose logging[​](#enable-verbose-logging "Direct link to Enable verbose logging") ``` LOG_LEVEL=verbose aztec start --local-network ``` ### Contract logging[​](#contract-logging "Direct link to Contract logging") See the full [Logging from Contracts](/developers/testnet/docs/aztec-nr/logging.md) guide for all available log functions and `LOG_LEVEL` configuration. ``` use aztec::oracle::logging::{debug_log, debug_log_format}; ``` ### Check contract registration[​](#check-contract-registration "Direct link to Check contract registration") ``` await wallet.getContractMetadata(myContractInstance.address); ``` ### Decode L1 errors[​](#decode-l1-errors "Direct link to Decode L1 errors") Check hex errors against [Errors.sol](https://github.com/AztecProtocol/aztec-packages/blob/v6.0.0-rc.1/l1-contracts/src/core/libraries/Errors.sol) ## Tips[​](#tips "Direct link to Tips") * Always check logs before diving into circuit errors * State-related errors often indicate timing issues * Array overflow errors mean you hit transaction limits * Use debug WASM for detailed stack traces * Profile transactions when errors are unclear ## Next steps[​](#next-steps "Direct link to Next steps") * [Circuit Architecture](/developers/testnet/docs/foundational-topics/advanced/circuits.md) * [Call Types](/developers/testnet/docs/foundational-topics/call_types.md) * [Aztec.nr Dependencies](/developers/testnet/docs/aztec-nr/framework-description/dependencies.md) --- # Profiling Transactions This guide shows you how to profile Aztec transactions to understand gate counts and identify optimization opportunities. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * `aztec` command installed ([see installation](/developers/testnet/getting_started_on_local_network.md)) * Aztec contract compiled (`aztec compile`) * Basic understanding of proving and gate counts ## Choosing a profiling tool[​](#choosing-a-profiling-tool "Direct link to Choosing a profiling tool") Aztec provides three ways to profile. Each serves a different purpose: | Tool | What it measures | Needs deployment? | When to use | | ------------------------------------------------- | --------------------------------------------------------- | ----------------- | -------------------------------------------------------- | | `aztec profile gates` | Per-function gate counts | No | Quick check of individual function costs after compiling | | `aztec profile flamegraph` | Per-function flamegraph SVG | No | Deep-dive into where gates come from inside a function | | `aztec-wallet profile` / `.profile()` in aztec.js | Full transaction gate count including all kernel circuits | Yes\* | Understanding the true cost of a transaction end-to-end | \* `aztec-wallet profile` and `ContractFunctionInteraction.profile()` require a deployed contract. However, `DeployMethod.profile()` in aztec.js can profile deployment transactions before the contract exists. In most cases, start with `aztec profile gates` for a quick overview, then use the full transaction profiling tools when you need to understand kernel overhead. ## Quick profiling with `aztec profile`[​](#quick-profiling-with-aztec-profile "Direct link to quick-profiling-with-aztec-profile") These commands work on compiled artifacts directly — no deployment or running network required. ### Gate counts[​](#gate-counts "Direct link to Gate counts") ``` # Compile your contract aztec compile # Get gate counts for all functions aztec profile gates ./target ``` Example output: ``` Gate counts: ──────────────────────────────────────────────────────────────────── my_contract-MyContract::constructor 5,200 my_contract-MyContract::my_function 14,832 my_contract-MyContract::transfer 31,559 ──────────────────────────────────────────────────────────────────── Total: 3 circuit(s) ``` These are the gate counts for your contract functions alone, **without** kernel circuit overhead. See [Understanding kernel overhead](#understanding-kernel-overhead) for how this translates to total transaction cost. BB binary `aztec profile` needs the Barretenberg (`bb`) backend binary. It is auto-detected from the `@aztec-foundation/bb.js` package. If auto-detection fails, set the `BB` environment variable: ``` BB=/path/to/bb aztec profile gates ./target ``` Machine-readable output For build automation, use `--json` to emit gate counts as a JSON array. Each entry has `name`, `type` (`contract-function` or `program`), and `gates`: ``` aztec profile gates --json ./target ``` ### Flamegraphs[​](#flamegraphs "Direct link to Flamegraphs") To generate an interactive flamegraph SVG for a specific function: ``` aztec profile flamegraph ./target/my_contract-MyContract.json my_function ``` This outputs a file like `my_contract-MyContract-my_function-flamegraph.svg` in the same directory. Open it in a browser for an interactive view where: * **Width** represents gate count * **Height** represents call stack depth * **Wide sections** indicate optimization targets tip If `noir-profiler` is not on your PATH, set the `PROFILER_PATH` environment variable: ``` PROFILER_PATH=/path/to/noir-profiler aztec profile flamegraph ./target/my_contract-MyContract.json my_function ``` ## Full transaction profiling[​](#full-transaction-profiling "Direct link to Full transaction profiling") The tools above measure individual function gate counts. To understand the **total** proving cost of a transaction — including account entrypoints and kernel circuits — use `aztec-wallet profile` or `.profile()` in aztec.js. These require a running network and, in most cases, a deployed contract. The exception is `DeployMethod.profile()` in aztec.js, which can profile deployment transactions before the contract exists. ### Profile with aztec-wallet[​](#profile-with-aztec-wallet "Direct link to Profile with aztec-wallet") Use the `profile` command instead of `send` to get detailed gate counts: ``` # Import test accounts aztec-wallet import-test-accounts # Deploy your contract aztec-wallet deploy MyContractArtifact \ --from accounts:test0 \ --args [CONSTRUCTOR_ARGS] \ -a mycontract # Profile a function call aztec-wallet profile my_function \ -ca mycontract \ --args [FUNCTION_ARGS] \ -f accounts:test0 ``` #### Reading the output[​](#reading-the-output "Direct link to Reading the output") The profile command outputs a per-circuit breakdown: ``` Per circuit breakdown: Function name Time Gates Subtotal -------------------------------------------------------------------------------- - SchnorrAccount:entrypoint 12.34ms 21,724 21,724 - private_kernel_init 23.45ms 45,351 67,075 - MyContract:my_function 15.67ms 31,559 98,634 - private_kernel_inner 34.56ms 78,452 177,086 Total gates: 177,086 (Biggest circuit: private_kernel_inner -> 78,452) ``` Key metrics: * **Gates**: Circuit complexity for each step * **Subtotal**: Accumulated gate count * **Time**: Execution time per circuit Notice that the kernel circuits (`private_kernel_init`, `private_kernel_inner`) appear alongside your contract functions. These are protocol overhead — see [Understanding kernel overhead](#understanding-kernel-overhead). ### Profile with aztec.js[​](#profile-with-aztecjs "Direct link to Profile with aztec.js") ``` const result = await contract.methods.my_function(args).profile({ from: walletAddress, profileMode: "full", skipProofGeneration: true, }); // Access gate counts from execution steps for (const step of result.executionSteps) { console.log(`${step.functionName}: ${step.gateCount} gates`); } // Access timing information console.log("Total time:", result.stats.timings.total, "ms"); ``` #### Profile modes[​](#profile-modes "Direct link to Profile modes") * `gates`: Gate counts per circuit * `execution-steps`: Detailed execution trace with bytecode and witnesses * `full`: Complete profiling information (gates + execution steps) Set `skipProofGeneration: true` for faster iteration when you only need gate counts. ## Generate flamegraphs with noir-profiler[​](#generate-flamegraphs-with-noir-profiler "Direct link to Generate flamegraphs with noir-profiler") For deeper analysis of individual contract functions beyond what `aztec profile flamegraph` provides, you can use the Noir profiler directly. The profiler is installed automatically with Nargo (starting noiru
프로젝트로 돌아가기