bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 51쪽
://github.com/aztec-labs-eng/aztec-nr). To add it as a dependency, point to the aztec-packages repository:
```
[dependencies]
public_checks = { git = "https://github.com/aztec-labs-eng/aztec-node/", tag = "v6.0.0-rc.1", directory = "noir-projects/noir-contracts/contracts/standard/public_checks_contract" }
```
Even with the public checks contract, achieving good privacy is hard. For example, if the value being checked against is unique and stored in the contract's public storage, it's then simple to find private transactions that are using that value in the enqueued public reads, and therefore link them to this contract. For this reason it is encouraged to try to avoid public function calls and instead privately read [Delayed Public Mutable](/developers/testnet/docs/aztec-nr/framework-description/state_variables.md#delayedpublicmutable) state when possible.
### Public Execution[](#public-execution "Direct link to Public Execution")
Contract functions marked with `#[external("public")]` can only be called publicly, and are executed by the sequencer. The computation model is very similar to the EVM: all state, parameters, etc. are known to the entire network, and no data is private. Static execution like the EVM's `STATICCALL` is possible too, with similar semantics (state can be accessed but not modified, etc.).
note
The AVM supports a subset of Noir's cryptographic operations. Signature verification (ECDSA) is not available in public functions. See [AVM Cryptographic Compatibility](/developers/testnet/docs/foundational-topics/advanced/circuits/avm_compatibility.md) for details.
Since private calls are always run in a user's device, it is not possible to perform any private execution from a public context. A reasonably good mental model for public execution is that of an EVM in which some work has already been done privately, and all that is known about it is its correctness and side-effects (new notes and nullifiers, enqueued public calls, etc.). A reverted public execution will also revert the private side-effects.
Public functions in other contracts can be called both regularly and statically, just like on the EVM.
public\_call
```
self.enqueue(Token::at(config.accepted_asset).transfer_in_public(
self.msg_sender(),
self.address,
max_fee,
authwit_nonce,
));
```
> [Source code: noir-projects/noir-contracts/contracts/fees/fpc\_contract/src/main.nr#L153-L160](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L153-L160)
note
Public functions can be called either directly in a public context (as shown above), or asynchronously by enqueuing from a private context (as shown in the [Public Calls](#public-calls) section).
### Utility[](#utility "Direct link to Utility")
Contract functions marked with `#[external("utility")]` are never proven as part of a transaction, even when called from a private function. They are invoked by applications that interact with contracts for:
* **State queries**: Reading from both private and public state via an offchain client
* **Local state management**: Modifying contract-related PXE state (e.g., processing logs in Aztec.nr)
Utility functions can also be called from other utility functions, and from private functions as unconstrained code. Calls that cross a contract boundary require wallet authorization. See [utility calls](/developers/testnet/docs/aztec-nr/framework-description/calling_contracts.md#utility-calls) for how to make them.
Since utility execution is unconstrained and relies heavily on oracle calls, no guarantees are made on the correctness of results. However, you can verify that the bytecode being executed is correct, since a contract's address includes a commitment to all of its utility functions.
### aztec.js[](#aztecjs "Direct link to aztec.js")
There are two main ways to execute an Aztec contract function using the `aztec.js` library, with close similarities to their [JSON-RPC counterparts](#json-rpc).
#### `simulate`[](#simulate "Direct link to simulate")
This is used to get a result out of an execution, either private or public. It creates no transaction and spends no gas. The mental model is fairly close to that of [`eth_call`](#eth_call), in that it can be used to call any type of function, simulate its execution and get a result out of it. `simulate` is also the only way to run [utility functions](#utility).
simulate\_function
```
const { result: balance } = await token.methods
.balance_of_public(aliceAddress)
.simulate({ from: aliceAddress });
console.log(`Alice's token balance: ${balance}`);
```
> [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L151-L157](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L151-L157)
warning
No correctness is guaranteed on the result of `simulate`! Correct execution is entirely optional and left up to the client that handles this request.
#### `send`[](#send "Direct link to send")
This creates a transaction, generates proofs for private execution, broadcasts the transaction to the network, and returns a receipt. This is how transactions are sent, getting them to be included in blocks and spending gas. It is similar to [`eth_sendTransaction`](#eth_sendtransaction), except it also performs work on the user's device, namely the production of the proof for the private part of the transaction.
send\_tx
```
await contract.methods.buy_pack(seed).send({ from: firstPlayer });
```
> [Source code: yarn-project/end-to-end/src/automine/card\_game.test.ts#L127-L129](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/yarn-project/end-to-end/src/automine/card_game.test.ts#L127-L129)
You can also use `send` to check for execution failures in testing contexts by expecting the transaction to throw:
local-tx-fails
```
await expect(
claimContract.methods.claim(anotherDonationNote, donorAddress).send({ from: unrelatedAddress }),
).rejects.toThrow('confirmed_note.owner == self.msg_sender()');
```
> [Source code: yarn-project/end-to-end/src/automine/token/crowdfunding\_and\_claim.test.ts#L221-L225](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/yarn-project/end-to-end/src/automine/token/crowdfunding_and_claim.test.ts#L221-L225)
## Next Steps[](#next-steps "Direct link to Next Steps")
* [State Management](/developers/testnet/docs/foundational-topics/state_management.md) - Learn how private and public state works in Aztec
* [Transactions](/developers/testnet/docs/foundational-topics/transactions.md) - Understand the transaction lifecycle
* [Contract Creation](/developers/testnet/docs/foundational-topics/contract_creation.md) - Deploy and interact with contracts
* [Declaring Storage](/developers/testnet/docs/aztec-nr/framework-description/state_variables.md) - Define storage in your contracts
---
# Contract Deployment
In the Aztec protocol, contracts are created as *instances* of contract *classes*. Unlike Ethereum where deployment is binary (deployed or not), Aztec contracts progress through multiple states before they are fully operational.
## Contract Lifecycle Overview[](#contract-lifecycle-overview "Direct link to Contract Lifecycle Overview")
Aztec contracts go through these states:
1. **Contract Class Registration** - Publishing the contract bytecode to the network
2. **Contract Instance Creation** - Computing a deterministic address from class, salt, and initialization parameters
3. **Initialization** - Running the constructor to set up initial state
4. **Public Deployment** - Broadcasting the instance to the network for public function calls
5. **Private Function Broadcasting** - Sharing private function artifacts offchain (optional)
Not every contract needs every state. A private-only contract can skip class registration and public deployment entirely. See the [Contract Deployment Quick Reference](/developers/testnet/docs/aztec-nr/contract_readiness_states.md) for a practical guide on which steps your contract needs.
## Contract Classes[](#contract-classes "Direct link to Contract Classes")
A contract class is a collection of state variable declarations, and related private, public and utility functions. Contract classes don't have state, they just define code (storage structure and function logic). A contract class cannot be called; only a contract instance can be called.
### Key Benefits of Contract Classes[](#key-benefits-of-contract-classes "Direct link to Key Benefits of Contract Classes")
Contract classes simplify code reuse by making implementations a first-class citizen in the protocol. With a single class registration, multiple contract instances can be deployed that reference it, reducing deployment costs. Classes also facilitate upgradability by decoupling state from code, making it easier for an instance to switch to different code while retaining its state.
### Structure of a Contract Class[](#structure-of-a-contract-class "Direct link to Structure of a Contract Class")
A contract class includes:
* `artifact_hash`: Hash of the contract artifact
* `private_functions_root`: Merkle root of the private functions tree
* `packed_public_bytecode`: Packed bytecode representation of the AVM bytecode for all public functions
The specification of the artifact hash is not enforced by the protocol. It should include commitments to utility functions code and compilation metadata. It is intended to be used by clients to verify that an offchain fetched artifact matches a registered class.
### Contract Class Registration[](#contract-class-registration "Direct link to Contract Class Registration")
A contract class is published by calling a private `publish` function in a canonical `ContractClassRegistry` contract, which emits a registration nullifier. This process guarantees that the public bytecode for a contract class is publicly available, which is required for deploying contract instances.
Contract class registration can be skipped if there are no public functions, and the contract will still be usable privately. However, if you have public functions, you must either register the class before deployment or skip public deployment entirely (only private functions will be callable).
## Contract Instances[](#contract-instances "Direct link to Contract Instances")
A deployed contract is effectively an instance of a contract class. It always references a contract class, which determines what code it executes when called. A contract instance has both private and public state, as well as an address that serves as its identifier.
### Structure of a Contract Instance[](#structure-of-a-contract-instance "Direct link to Structure of a Contract Instance")
A contract instance includes:
* `salt`: User-generated pseudorandom value for uniqueness
* `deployer`: Optional address of the contract deployer. Zero for universal deployment
* `original_contract_class_id`: Identifier of the contract class the instance was deployed with. Updating the instance to a new class via the ContractInstanceRegistry does not change this value, since it is part of the address preimage
* `initialization_hash`: Hash of the selector and arguments to the constructor
* `immutables_hash`: Hash of the contract's compile-time immutable state
* `public_keys`: Public keys participating in address derivation (nullifier, incoming viewing, outgoing viewing, tagging, message-signing, and fallback keys). Only the incoming viewing key is held as an elliptic curve point; the other five are held as their `hash_public_key` digests.
### Instance Address[](#instance-address "Direct link to Instance Address")
The address of a contract instance is computed as the hash of the elements in its structure. This computation is deterministic, allowing users to precompute the expected deployment address of their contract, including account contracts.
### Contract Initialization vs. Public Deployment[](#contract-initialization-vs-public-deployment "Direct link to Contract Initialization vs. Public Deployment")
Aztec makes an important distinction between initialization and public deployment:
1. **Initialization**: A contract instance is considered initialized once it emits an initialization nullifier, meaning it can only be initialized once. The default state for any address is uninitialized. A user who knows the preimage of the address can still issue a private call into a function in the contract, as long as that function doesn't assert that the contract has been initialized.
2. **Public Deployment**: A contract instance is considered publicly deployed when it has been broadcast to the network via the `publish_for_public_execution` function in the canonical `ContractInstanceRegistry` contract, which emits a deployment nullifier. All public function calls to an undeployed address fail, since the contract class is not known to the network.
### Initialization[](#initialization "Direct link to Initialization")
Contract constructors are not enshrined in the protocol, but handled at the application circuit level. Constructors are methods used for initializing a contract, either private or public, and contract classes may declare more than a single constructor. They can be declared by the `#[initializer]` macro. You can read more about how to use them on the [defining initializer functions](/developers/testnet/docs/aztec-nr/framework-description/functions/how_to_define_functions.md#define-initializer-functions) page.
A contract must ensure:
* It is initialized at most once
* It is initialized using the method and arguments defined in its address preimage
* It is initialized by its deployer (if non-zero)
* Functions dependent on initialization cannot be invoked until the contract is initialized
Functions in a contract may skip the initialization check.
## Verification of Executed Code[](#verification-of-executed-code "Direct link to Verification of Executed Code")
When a function is called on a contract instance, the protocol circuits verify that the executed code matches what was registered. For private functions, the circuit checks that the function's verification key hash exists in the `private_functions_root` of the contract class. For public functions, the AVM verifies that the bytecode matches the registered `packed_public_bytecode`. This verification ensures that contracts execute the exact code that was published during class registration.
## Genesis Contracts[](#genesis-contracts "Direct link to Genesis Contracts")
The `ContractInstanceRegistry` and `ContractClassRegistry` contracts are protocol contracts that exist from the genesis of the Aztec Network at predefined addresses. They are necessary for deploying other contracts to the network.
## Private Function Broadcasting[](#private-function-broadcasting "Direct link to Private Function Broadcasting")
Private function artifacts can be shared offchain so others can call your private functions. This is optional—callers who already have the artifacts don't need them broadcast. This step is only necessary when you want external parties to interact with your contract's private functions without having obtained the artifacts through other means.
## Proving Contract States[](#proving-contract-states "Direct link to Proving Contract States")
Your contract can verify the deployment or initialization state of other contracts. This is useful for:
* Ensuring a dependency contract is deployed before interacting
* Access control based on contract state
* Conditional logic based on initialization
```
use aztec::history::deployment::{
assert_contract_bytecode_was_not_published_by,
assert_contract_bytecode_was_published_by,
assert_contract_was_initialized_by,
assert_contract_was_not_initialized_by,
};
// Prove a contract's bytecode was published by a given block
assert_contract_bytecode_was_published_by(block_header, contract_address);
// Prove a contract's bytecode was NOT published by a given block
assert_contract_bytecode_was_not_published_by(block_header, contract_address);
// Prove a contract was initialized by a given block
// (init_hash is the contract's initialization hash, obtainable via get_contract_instance)
assert_contract_was_initialized_by(block_header, contract_address, init_hash);
// Prove a contract was NOT initialized by a given block
assert_contract_was_not_initialized_by(block_header, contract_address, init_hash);
```
These functions prove inclusion or non-inclusion of the corresponding nullifiers in the nullifier tree at a given block.
## Further reading[](#further-reading "Direct link to Further reading")
* [Contract Deployment Quick Reference](/developers/testnet/docs/aztec-nr/contract_readiness_states.md) - Practical guide for which deployment steps your contract needs
* [Deploying Contracts](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md) - Deploy contracts using TypeScript
* [DApp Development Tutorial](/developers/testnet/docs/tutorials/js_tutorials/aztecjs-getting-started.md) - Build a complete application
* [Communicating Cross-Chain](/developers/testnet/docs/aztec-nr/framework-description/ethereum_aztec_messaging.md) - Portal contracts and L1/L2 messaging
---
# L1-L2 Communication (Portals)
<!-- -->
In Aztec, *portals* facilitate communication between L1 and L2. Unlike typical L2 solutions that rely on synchronous communication, Aztec's privacy-first design and the way transactions are processed (kernel proofs built on historical data) make direct calls between L1 and L2 impossible while maintaining privacy. Portals solve this by acting as bridges for asynchronous message passing, transmitting messages from public functions in L1 to private functions in L2 and vice versa.
## Objective[](#objective "Direct link to Objective")
The goal is to set up a minimal-complexity mechanism, that will allow a base-layer (L1) and the Aztec Network (L2) to communicate arbitrary messages such that:
* L2 functions can `call` L1 functions.
* L1 functions can `call` L2 functions.
* Messages have minimal impact on rollup block size.
## High Level Overview[](#high-level-overview "Direct link to High Level Overview")
This document will contain communication abstractions that we use to support interaction between *private* functions, *public* functions and Layer 1 portal contracts.
Fundamental restrictions for Aztec:
* L1 and L2 have very different execution environments. Operations that are cheap on L1 are often expensive on L2 and vice versa. For example, `keccak256` is cheap on L1 but very expensive on L2.
* *Private* function calls are fully "prepared" and proven by the user, which provides the kernel proof along with commitments and nullifiers to the sequencer.
* *Public* functions altering public state (updatable storage) must be executed at the current "head" of the chain, which only the sequencer can ensure, so these must be executed separately to the *private* functions.
* *Private* and *public* functions within Aztec are therefore ordered such that *private* functions are executed first, then *public* functions.
* Messages are consumables, and can only be consumed by the recipient. See [Message Boxes](#message-boxes) for more information.
With the aforementioned restrictions taken into account, cross-chain messages can be operated in a similar manner to when *public* functions must transmit information to *private* functions. In such a scenario, a "message" is created and conveyed to the recipient for future use. It is worth noting that any call made between different domains (*private, public, cross-chain*) is unilateral in nature. In other words, the caller is unaware of the outcome of the initiated call until told when some later rollup is executed (if at all). This can be regarded as message passing, providing us with a consistent mental model across all domains, which is convenient.
As an illustration, suppose a private 프로젝트로 돌아가기