Aztec 백서

Aztec

원문

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

Private-to-private calls[​](#private-to-private-calls "Direct link to Private-to-private calls") private\_call ``` let _ = self.call(Token::at(stable_coin).burn_private(from, amount, authwit_nonce)); ``` > [Source code: noir-projects/noir-contracts/contracts/app/lending\_contract/src/main.nr#L231-L233](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L231-L233) ### Public-to-public calls[​](#public-to-public-calls "Direct link to Public-to-public calls") From a public function, call other public functions directly: ``` self.call(Token::at(token_address).transfer_in_public(recipient, amount)); ``` Capture return values by assigning the result: ``` let balance = self.view(Token::at(token_address).balance_of_public(account)); ``` Use `self.view()` for read-only calls that cannot modify state. ### Private-to-public calls[​](#private-to-public-calls "Direct link to Private-to-public calls") From a private function, enqueue public function calls for later execution: ``` self.enqueue(Token::at(token_address).mint_to_public(recipient, amount)); ``` info Public functions execute after all private execution completes. Return values are not available in the private context. Learn more about [call types](/developers/testnet/docs/foundational-topics/call_types.md). ## Utility calls[​](#utility-calls "Direct link to Utility calls") Utility functions can call other utility functions. These calls run entirely offchain in PXE and are never proven, so no guarantees are made on the correctness of their results. ### Utility-to-utility calls[​](#utility-to-utility-calls "Direct link to Utility-to-utility calls") From a utility function, use `self.call()` as with other call types: ``` let balance = self.call(Token::at(token_address).get_balance_of(owner)); ``` To call a utility function of your own contract, use the `self.call_self` stubs instead: ``` self.call_self.my_utility_function(args) ``` ### Private-to-utility calls[​](#private-to-utility-calls "Direct link to Private-to-utility calls") Private functions can also call utility functions, through `self.utility`. The call executes unconstrained code, so it must be wrapped in `unsafe`, and its result is not proven: use it to inform logic, never as an input to a constrained assertion without validating it first. ``` // Safety: result is unconstrained let balance = unsafe { self.utility.call(Token::at(token_address).get_balance_of(owner)) }; ``` The same-contract stubs are available here as `self.utility.call_self`: ``` unsafe { self.utility.call_self.my_utility_function(args) } ``` Public functions cannot call utility functions: they run on the sequencer, which has no access to private state or PXE. ### Cross-contract authorization[​](#cross-contract-authorization "Direct link to Cross-contract authorization") A utility call to the calling contract itself always succeeds. A call to a *different* contract can expose that contract's private state to the caller, so PXE asks the wallet to authorize it before proceeding. If the wallet denies the call, or no `authorizeUtilityCall` hook is configured, the simulation fails with `Cross-contract utility call denied`. See [execution hooks](/developers/testnet/docs/foundational-topics/pxe/execution_hooks.md#authorizeutilitycall) for how wallets handle these requests, and for authorizing targets in Noir tests with `with_authorized_utility_call_targets`. ### `msg_sender` in nested utility calls[​](#msg_sender-in-nested-utility-calls "Direct link to msg_sender-in-nested-utility-calls") A utility function called from another contract can read the calling contract's address via `self.msg_sender()`, mirroring private and public functions. A utility function invoked directly by an application has no caller: `self.msg_sender()` panics, and `self.context.maybe_msg_sender()` returns `Option::none()`. Within a simulation PXE takes this value from the actual call graph, but utility execution as a whole is unconstrained, so contracts must not rely on it as a security guarantee. --- # Contract Artifacts Compiling an Aztec contract produces a contract artifact file (`.json`) containing everything needed to interact with that contract: its name, functions, their interfaces, and compiled bytecode. Since private function bytecode is never published to the network, you need this artifact file to call private functions. Most developers don't need this When you [compile a contract](/developers/testnet/docs/aztec-nr/compiling_contracts.md) and use [`aztec codegen`](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md#generate-typescript-bindings), you get type-safe TypeScript classes that handle artifacts automatically. This page is useful if you're: * Building custom tooling around Aztec contracts * Debugging compilation or deployment issues * Understanding what data is available in artifacts ## Where to Find Artifacts[​](#where-to-find-artifacts "Direct link to Where to Find Artifacts") After running `aztec compile`, artifacts are output to the `target/` directory: ``` target/ └── my_contract-MyContract.json # Contract artifact ``` Use `aztec codegen` to generate TypeScript bindings from these artifacts for type-safe contract interaction. ## Contract Artifact Structure[​](#contract-artifact-structure "Direct link to Contract Artifact Structure") A contract artifact contains: * **`name`**: The contract name as defined in Noir * **`functions`**: Array of function artifacts (private, public dispatch, and utility functions) * **`nonDispatchPublicFunctions`**: Public function ABIs (excluding the dispatch function) * **`outputs`**: Exported structs and globals from the contract * **`storageLayout`**: Storage slot mappings for contract state * **`fileMap`**: Source file mappings for debugging ## Exported globals[​](#exported-globals "Direct link to Exported globals") Add `#[abi(tag)]` to a public Noir global to export its name and value in the contract artifact. A tag groups related globals, and you can apply the same tag to multiple globals: ``` use aztec::macros::aztec; #[aztec] pub contract Globals { #[abi(constants)] pub global EXPORTED_FIELD_CONSTANT: Field = 1234; #[abi(constants)] pub global EXPORTED_STRING_CONSTANT: str<8> = "exported"; #[abi(limits)] pub global EXPORTED_LIMIT_CONSTANT: u32 = 100; #[abi(constants)] #[abi(limits)] pub global EXPORTED_SHARED_CONSTANT: u32 = 7; } ``` The example creates two groups under `outputs.globals`: `constants` and `limits`. Each group is an array of `{ name, value }` entries. Stacking attributes on `EXPORTED_SHARED_CONSTANT` exports the same global under both tags. When working directly with an artifact, use `getGlobalsByTag` to return the named entries for one tag as raw `AbiValue` objects: ``` import { getGlobalsByTag } from '@aztec-labs/aztec.js/abi'; const constants = getGlobalsByTag(GlobalsContract.artifact, 'constants'); const exportedString = constants.EXPORTED_STRING_CONSTANT; // { kind: 'string', value: 'exported' } ``` ## Function Properties[​](#function-properties "Direct link to Function Properties") Each function in the artifact includes: | Property | Description | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `name` | Function name as defined in Noir | | `functionType` | One of `private`, `public`, or `utility` | | `isOnlySelf` | If `true`, function can only be called from within the same contract | | `isStatic` | If `true`, function cannot alter state | | `isInitializer` | If `true`, function can be used as a constructor | | `parameters` | Array of input parameters with name, type, and visibility | | `returnType` | The type the function returns, omitted when it returns nothing. Multiple return values are expressed as a single `tuple` type | | `errorTypes` | Custom error types the function can throw | | `bytecode` | Compiled ACIR bytecode (base64 encoded) | | `verificationKey` | Verification key for private functions (optional) | | `debugSymbols` | Compressed debug information linking to source code | ### Function Types[​](#function-types "Direct link to Function Types") * **`private`**: Executed and proved locally by the client. Bytecode is not published to the network. * **`public`**: Executed and proved by the sequencer. Bytecode is published to the network. * **`utility`**: Executed locally to compute information (e.g., view functions). Cannot be called in transactions. ## Parameter and Return Types[​](#parameter-and-return-types "Direct link to Parameter and Return Types") Parameters and return values use these type definitions: | Type | Description | | --------- | ----------------------------------------------------------------- | | `field` | A field element in the BN254 curve's scalar field | | `boolean` | True/false value | | `integer` | Whole number with `sign` (`signed`/`unsigned`) and `width` (bits) | | `array` | Collection of elements with `length` and element `type` | | `string` | Character sequence with fixed `length` | | `struct` | Composite type with named `fields` and a `path` identifier | | `tuple` | Unnamed composite type with ordered `fields` | Parameter visibility can be `public`, `private`, or `databus`. ## Next Steps[​](#next-steps "Direct link to Next Steps") * [Compile contracts](/developers/testnet/docs/aztec-nr/compiling_contracts.md) to generate artifacts * [Deploy contracts](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md) using generated TypeScript bindings * [Send transactions](/developers/testnet/docs/aztec-js/how_to_send_transaction.md) to interact with deployed contracts --- # Contract Structure High-level structure of how Aztec smart contracts including the different components. ## Directory structure[​](#directory-structure "Direct link to Directory structure") When you create a new project with `aztec new my_project`, it generates a two-crate Noir workspace: a contract crate for your smart contract code and a sibling test crate for Noir tests. layout of an aztec contract project ``` ─── my_project ├── Nargo.toml <-- workspace file ([workspace] members) ├── my_project_contract │ ├── Nargo.toml <-- contract package (type = "contract") │ └── src │ └── main.nr <-- your contract └── my_project_test ├── Nargo.toml <-- test package (type = "lib") └── src └── lib.nr <-- Noir tests ``` The top-level `Nargo.toml` is a workspace file. Contract dependencies live in `my_project_contract/Nargo.toml` (with `type = "contract"`). Tests live in the separate `my_project_test` crate and import the contract by package name (for example, `use my_project_contract::MyContract;`) — see [Testing Contracts](/developers/testnet/docs/aztec-nr/testing_contracts.md). To add another contract to the same workspace, run `aztec new <name>` from inside the workspace directory; this adds a new `<name>_contract` and `<name>_test` crate pair. To initialize a project inside an existing empty directory, `cd` into it and run `aztec init`, which scaffolds the same two-crate layout pre-populated with a runnable [Counter example](/developers/testnet/docs/tutorials/contract_tutorials/counter_contract.md) (use `aztec new` if you want a blank starting point instead). See the vanilla Noir docs for [more info on packages](https://noir-lang.org/docs/project_structure/crates_and_packages). ## Contract block[​](#contract-block "Direct link to Contract block") All contracts start with importing the required files and declaring a contract using the `contract` keyword: ``` // import the `aztec` macro from Aztec.nr use aztec::macros::aztec; // use the 'contract' keyword to declare a contract, applying the `aztec` macro #[aztec] pub contract MyContract { // contract code here } ``` By convention, contracts are named in `PascalCase`. The `#[aztec]` macro performs a lot of the low-level operations required to take a circuit language like Noir and build smart contracts out of it - including automatically creating external interfaces, inserting standard contract functions, etc. **All Aztec smart contracts must have this macro applied to them.** **Note:** each Noir crate (package) can only have *a single* contract. If you are writing a multi-contract system, then each of them needs to be in their own separate crate. To learn more about crates and packages, visit the [Noir documentation](https://noir-lang.org/docs/project_structure/crates_and_packages). ## Imports[​](#imports "Direct link to Imports") Aside from the [`#[aztec]`](/aztec-nr-api/testnet/noir_aztec/macros/fn.aztec) macro import, all other imports need to go *inside* the `contract` block - this is because `contract` acts like `mod`, creating a new [module](https://noir-lang.org/docs/project_structure/modules). ``` use aztec::macros::aztec; #[aztec] pub contract MyContract { // other imports go here use aztec::state_vars::{PrivateMutable, PrivateSet}; } ``` **Note:** [Noir's VSCode extension](/developers/testnet/docs/aztec-nr/installation.md) is able to take care of most imports and put them in the correct place automatically. ## State Variables[​](#state-variables "Direct link to State Variables") With the boilerplate out of the way, it is now the time to begin defining the contract logic. It is recommended to start development by understanding the shape the *state* of the contract will have: * Which values will be private? * Which will be public? * What properties are required (is mutability or immutability needed? Is there a single global value, like a token total supply, or does each user get one, like a balance?). In Solidity, this is done by simply declaring variables inside of the contract, like so: ``` contract MyContract { uint128 public my_public_state_variable; } ``` In Aztec, defining state requires a few more steps, as there are both private and public variables (where these keywords refer to the privacy of the variable rather than their accessibility), and multiple *kinds* of state variables. We define state using a [`struct`](https://noir-lang.org/docs/language/data_types/structs) that will hold the entire contract state. We call this struct *the storage struct*, and each variable inside this struct is called [*a state variable*.](/developers/testnet/docs/aztec-nr/framework-description/state_variables.md) ``` use aztec::macros::aztec; #[aztec] pub contract MyContract { use aztec::{ macros::storage, state_vars::{Owned, PrivateMutable, PublicMutable} }; use uint_note::UintNote; // The storage struct must be named `Storage` and must have the `#[storage]` macro applied to it. // This struct must also have a generic type called C or Context. #[storage] struct Storage<Context> { // A private numeric value which can change over time. This value will be hidden, and only those with the secret can know its current value. my_private_state_variable: Owned<PrivateMutable<UintNote, Context>, Context>, // A public numeric value which can change over time. This value will be known to everyone and is equivalent to the Solidity example above. my_public_state_variable: PublicMutable<u128, Context>, } } ``` ## Events[​](#events "Direct link to Events") Like Solidity contracts, Aztec contracts can define events to notify that some state has changed. However, in Aztec, events can also be emitted privately, in which case only some users will learn of the event. [Events](/developers/testnet/docs/aztec-nr/framework-description/events_and_logs.md) are a struct marked with the `#[event]` macro: ``` #[event] struct Transfer { from: AztecAddress, to: AztecAddress, amount: u128, } ``` ## Functions[​](#functions "Direct link to Functions") Contracts are interacted with by invoking their `external` [functions](/developers/testnet/docs/aztec-nr/framework-description/functions.md). There are three kinds of `external` functions: * External **private** functions, which reveal nothing about their execution and are executed off chain on the user's device, producing a zero-knowledge proof of execution that is sent to the network as part of a transaction. * External **public** functions, which nodes in the network invoke publicly (like any `external` Solidity contract function). * External **utility** functions, which are executed off chain on the user's device by applications in order to display useful information, e.g. retrieve contract state. These are never part of a transaction. ``` use aztec::macros::aztec; #[aztec] contract MyContract { use aztec::macros::functions::external; use aztec::protocol::address::AztecAddress; #[external("private")] fn my_private_function(parameter_a: u128, parameter_b: AztecAddress) { // ... } #[external("public")] fn my_public_function(parameter_a: u128, parameter_b: AztecAddress) { // ... } #[external("utility")] unconstrained fn my_utility_function(parameter_a: u128, parameter_b: AztecAddress) { // ... } } ``` Contracts can also define `internal` functions, which cannot be called by other contracts (like any `internal` Solidity function). These exist to help organize your code, reuse functionality, etc. ### Current Limitations[​](#current-limitations "Direct link to Current Limitations") All `#[external]` contract functions must be defined *directly inside the `contract` block*, that is, in the same file. It is possible to define `#[internal]` and helper functions in `mod`s in other files, but not `#[external]` functions. **Noir does not feature inheritance** nor is there currently any other mechanism to extend and reuse contract logic. For example, you cannot take a token contract and extend it to add minting functionality, or reuse it in a liquidity pool. Like Vyper, the entire logic must live in a single file. We expect to lift some of these restrictions sometime after the release of Noir 1.0. ## Next steps[​](#next-steps "Direct link to Next steps") * [Define functions](/developers/testnet/docs/aztec-nr/framework-description/functions.md) - Learn about private, public, and utility functions * [Define storage](/developers/testnet/docs/aztec-nr/framework-description/state_variables.md) - Work with persistent state variables * [Compile your contract](/developers/testnet/docs/aztec-nr/compiling_contracts.md) - Build your contract artifact --- # Contract Upgrades Upgrades are not yet well supported by the framework Contract upgrades are currently a low-level protocol feature with minimal framework support. Before relying on them, be aware that: * Upgrades are hard to execute correctly, and need lots of careful testing. * State migrations are non-trivial and also require extensive testing. The new implementation must be compatible with all existing state, including public storage, private notes, and initialization status. * The `#[aztec]` macros are not at the moment built with upgrades in mind. Macro-generated code makes assumptions that upgrades can violate (for example, initialization checks in the new implementation can make all functions of already-deployed instances permanently uncallable), so users may need to drop the macros until support is added. * There is no additional tooling at the moment to help with upgrades, such as detection of storage layout compatibility between the old and new implementations. All in all, this feature is not well supported by the framework as of now, and should only be used with extreme care. Each contract instance refers to a contract class ID for its code. Upgrading a contract's implementation involves updating its current class ID to a new class ID, while retaining the original class ID for address verification. ## Original class ID[​](#original-class-id "Direct link to Original class ID") A contract stores the original contract class it was instantiated with. This original class
프로젝트로 돌아가기