bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 39쪽
cAddress, completer: AztecAddress) -> Field {
let commitment = self.internal._initialize_transfer_commitment(to, completer);
commitment.commitment()
}
```
This function returns `commitment.commitment()` — an opaque `Field` representing the commitment. The AIP-20 equivalent returns `commitment.to_field()` for `PartialUintNote`.
---
# Dripper (Development Faucet)
[Source](https://github.com/defi-wonderland/aztec-standards/tree/dev/src/dripper)
The `aztec-standards` repository also ships a **Dripper** contract — a convenience faucet for minting tokens into private or public balances during development. It is not a formal AIP standard and should not be used in production.
---
# Escrow
[Source](https://github.com/defi-wonderland/aztec-standards/tree/dev/src/escrow_contract)
The Escrow standard provides a minimal contract for holding tokens or NFTs on behalf of a single owner. Rather than storing the owner in mutable private state — which would require note discovery and decryption on every authorization check — the owner is encoded in the contract's own `salt` and thus baked into the contract address at deploy time. This makes authorization a simple field comparison against immutable deployment parameters: cheaper, simpler, and impossible to front-run.
## Escrow contract[](#escrow-contract "Direct link to Escrow contract")
```
#[aztec]
pub contract Escrow {
#[external("private")]
fn withdraw(token: AztecAddress, amount: u128, recipient: AztecAddress) {
self.internal._assert_msg_sender();
self.call(Token::at(token).transfer_private_to_private(
self.address, recipient, amount, 0,
));
}
#[external("private")]
fn withdraw_nft(nft: AztecAddress, token_id: Field, recipient: AztecAddress) {
self.internal._assert_msg_sender();
self.call(NFT::at(nft).transfer_private_to_private(
self.address, recipient, token_id, 0,
));
}
#[internal("private")]
fn _assert_msg_sender() {
let msg_sender = self.msg_sender();
let escrow_instance: ContractInstance = get_contract_instance(self.address);
assert(AztecAddress::from_field(escrow_instance.salt) == msg_sender, "Not Authorized");
}
}
```
The authorization check in `_assert_msg_sender` reads the `salt` field of the escrow's own `ContractInstance` and compares it against `msg_sender`. Because the `ContractInstance` is fixed at deployment time, this check cannot be spoofed by manipulating storage after deployment.
## Escrow logic library[](#escrow-logic-library "Direct link to Escrow logic library")
A DeFi protocol (like a lending market or DEX) often needs to give each user a personal escrow to hold collateral or pending settlements. The standard ships a companion library that lets the parent contract deterministically compute escrow addresses from its own address and the user's keys — no onchain deployment transaction required:
```
#[contract_library_method]
pub fn _get_escrow(
context: &mut PrivateContext,
escrow_class_id: Field,
master_secret_keys: MasterSecretKeys,
) -> AztecAddress {
let computed_public_keys: PublicKeys = _secret_keys_to_public_keys(master_secret_keys);
let escrow_instance = ContractInstance {
salt: context.this_address().to_field(),
deployer: AztecAddress::from_field(0),
original_contract_class_id: ContractClassId::from_field(escrow_class_id),
initialization_hash: 0,
public_keys: computed_public_keys,
};
escrow_instance.to_address()
}
#[contract_library_method]
pub fn _share_escrow(
context: &mut PrivateContext,
account: AztecAddress,
escrow: AztecAddress,
master_secret_keys: MasterSecretKeys,
) {
let event_struct = EscrowDetailsLogContent { escrow, master_secret_keys };
emit_event_in_private(context, event_struct).deliver_to(
account, MessageDelivery::onchain_constrained(),
);
}
```
`_get_escrow` reconstructs the escrow address deterministically from the calling contract's address (used as the salt) and a set of master secret keys. `_share_escrow` emits an encrypted log so that the designated `account` can discover the escrow address and the keys needed to access its notes. Without this notification, the user's PXE would have no way to find the escrow or decrypt notes held there. Constrained delivery ensures the log is validated against the note hash tree before the recipient's PXE trusts it.
---
# Generic Proxy
In Aztec, account contracts authorize every transaction the user sends and must be able to forward calls to any contract. However, Noir requires function signatures to be known at compile time, so an account contract cannot call an arbitrary function with an arbitrary number of arguments in a single generic entrypoint.
The Generic Proxy contract solves this by providing a fixed set of forwarding functions — one per argument count — that the account contract can call. This avoids hard-coding every possible target function signature while keeping the account contract simple.
```
#[aztec]
pub contract GenericProxy {
#[external("private")]
fn forward_private_0(target: AztecAddress, selector: FunctionSelector) {
let _ = self.context.call_private_function_no_args(target, selector);
}
#[external("private")]
fn forward_private_4(target: AztecAddress, selector: FunctionSelector, args: [Field; 4]) {
let _ = self.context.call_private_function(target, selector, args);
}
#[external("private")]
fn forward_private_4_and_return(
target: AztecAddress,
selector: FunctionSelector,
args: [Field; 4],
) -> Field {
let returns: Field =
self.context.call_private_function(target, selector, args).get_preimage();
returns
}
// ... forward_private_1 through forward_private_8
}
```
The proxy exposes a family of `forward_private_N` functions, each accepting a different fixed argument count. Because Noir's type system requires array lengths to be known at compile time, the contract implements one overload per arity rather than a single variadic function. The `_and_return` variant captures the return value from the callee and passes it back to the caller.
note
The Generic Proxy does not implement any access control by itself. Callers are responsible for ensuring that forwarding to `target` is appropriate. In most protocols, the proxy is called from within an account contract that enforces its own authorization rules before delegating to the proxy.
---
# Testing Contracts
This guide shows you how to test your Aztec smart contracts using Noir's `TestEnvironment` for fast, lightweight testing.
## Prerequisites[](#prerequisites "Direct link to Prerequisites")
* An Aztec contract project with functions to test
* Basic understanding of Noir syntax
tip
For complex cross-chain or integration testing, see the [TypeScript testing guide](/developers/testnet/docs/aztec-js/how_to_test.md).
## Write Aztec contract tests[](#write-aztec-contract-tests "Direct link to Write Aztec contract tests")
Use `TestEnvironment` from `aztec-nr` for contract unit testing:
* **Fast**: Lightweight environment with mocked components
* **Convenient**: Similar to Foundry for simple contract tests
* **Limited**: No rollup circuits or cross-chain messaging
For complex end-to-end tests, use [TypeScript testing](/developers/testnet/docs/aztec-js/how_to_test.md) with `aztec.js`.
## Run your tests[](#run-your-tests "Direct link to Run your tests")
Execute Aztec Noir tests using:
```
aztec test
```
### Test execution process[](#test-execution-process "Direct link to Test execution process")
1. Compile contracts
2. Run `aztec test`
warning
Always use `aztec test` instead of `nargo test`. The `TestEnvironment` requires the test environment oracle resolver provided by the `aztec` CLI.
## Keep tests in the test crate[](#keep-tests-in-the-test-crate "Direct link to Keep tests in the test crate")
`aztec new` and `aztec init` scaffold a workspace with two crates: a contract crate and a separate test crate. For `aztec new my_project`, these are `my_project_contract` and `my_project_test`. Keep all `#[test]` functions in the test crate, not in the contract crate.
If tests end up inside a contract crate, `aztec compile` emits a warning:
```
WARNING: Found tests in contract crate(s):
my_project_contract::test_something
Tests should be in a dedicated test crate, not in the contract crate.
```
The reason is **unnecessary recompilation**: a contract's compiled artifact depends on everything in its crate, so a test-only edit forces the contract to recompile even though its logic has not changed. Keeping tests in the separate test crate lets `aztec test` skip contract recompilation when only test code changed.
## Basic test structure[](#basic-test-structure "Direct link to Basic test structure")
`aztec new my_project` scaffolds a workspace with two crates: a `contract` crate that holds the contract code, and a separate `test` crate that holds your `#[test]` functions:
```
my_project/
├── Nargo.toml # [workspace] members = ["my_project_contract", "my_project_test"]
├── my_project_contract/
│ ├── Nargo.toml # type = "contract"
│ └── src/main.nr
└── my_project_test/
├── Nargo.toml # type = "lib", depends on my_project_contract
└── src/lib.nr # #[test] functions go here
```
The motivation for the split of contract and tests into its own crates is **faster iteration**: editing a test does not invalidate the contract's compiled artifact, so `aztec test` skips contract recompilation when only test code changed.
`aztec compile` warns if it finds `#[test]` functions inside a contract crate.
The generated test crate template imports the contract by package name and then initializes it:
```
// my_project_test/src/lib.nr
use aztec::test::helpers::test_environment::TestEnvironment;
use my_project_contract::Main;
#[test]
unconstrained fn test_constructor() {
let mut env = TestEnvironment::new();
let deployer = env.create_light_account();
let _contract_address = env.deploy("@my_project_contract/Main")
.with_private_initializer(deployer, Main::interface().constructor());
}
```
Because tests live in their own crate, we refer to the contract via its crate name using the `@crate_name/ContractName` syntax.
Test execution notes
* Tests run in parallel by default
* Use `unconstrained` functions for faster execution
* See all `TestEnvironment` methods [here](/aztec-nr-api/testnet/noir_aztec/test/helpers/test_environment/struct.TestEnvironment)
* It is always necessary to deploy a contract in order to test it
If you'll add arguments to your contract's constructor you pass them directly to the constructor function in the test:
```
let initializer = MyContract::interface().constructor(param1, param2);
```
Since Aztec contracts can be initialized both in private and public or they can be interacted with without any kind of initialization (see [Contract creation](/developers/testnet/docs/foundational-topics/contract_creation.md) for how Aztec's deployment model differs from Ethereum's) there are 3 options on the deployer:
```
let contract_address = deployer.with_private_initializer(owner, initializer);
let contract_address = deployer.with_public_initializer(owner, initializer);
let contract_address = deployer.without_initializer();
```
Reusable setup functions
Create a setup function to avoid repeating initialization code:
```
pub unconstrained fn setup(initial_value: Field) -> (TestEnvironment, AztecAddress, AztecAddress) {
let mut env = TestEnvironment::new();
let owner = env.create_light_account();
let initializer = MyContract::interface().constructor(initial_value, owner);
let contract_address = env.deploy("@my_project_contract/MyContract").with_private_initializer(owner, initializer);
(env, contract_address, owner)
}
#[test]
unconstrained fn test_something() {
let (env, contract_address, owner) = setup(42);
// Your test logic here
}
```
## Calling contract functions[](#calling-contract-functions "Direct link to Calling contract functions")
TestEnvironment provides methods for different function types:
### Private functions[](#private-functions "Direct link to Private functions")
```
// Call private function
env.call_private(caller, Token::at(token_address).transfer(recipient, 100));
// Returns the result
let result = env.call_private(owner, Contract::at(address).get_private_data());
```
### Public functions[](#public-functions "Direct link to Public functions")
```
// Call public function
env.call_public(caller, Token::at(token_address).mint_to_public(recipient, 100));
// View public state (read-only)
let balance = env.view_public(Token::at(token_address).balance_of_public(owner));
```
### Utility/Unconstrained functions[](#utilityunconstrained-functions "Direct link to Utility/Unconstrained functions")
```
// Simulate utility/view functions (unconstrained)
let total = env.execute_utility(Token::at(token_address).balance_of_private(owner));
// To set the `msg_sender` the utility function observes, use the `_opts` variant
let secret = env.execute_utility_opts(
ExecuteUtilityOptions::new().with_from(caller),
Registry::at(registry_address).get_app_siloed_secret(sender, recipient),
).map(|secrets| secrets.shared);
```
Helper function pattern
Create helper functions for common assertions:
```
pub unconstrained fn check_balance(
env: TestEnvironment,
token_address: AztecAddress,
owner: AztecAddress,
expected: u128,
) {
assert_eq(
env.execute_utility(Token::at(token_address).balance_of_private(owner)),
expected
);
}
```
## Creating accounts[](#creating-accounts "Direct link to Creating accounts")
Two types of accounts are available:
```
// Light account - fast, limited features
let owner = env.create_light_account();
// Contract account - full features, slower
let owner = env.create_contract_account();
```
Account type comparison
**Light accounts:**
* Fast to create
* Work for simple transfers and tests
* Cannot process authwits
* No account contract deployed
**Contract accounts:**
* Required for authwit testing
* Support account abstraction features
* Slower to create (deploys account contract)
* Needed for cross-contract authorization
Choosing account types
```
pub unconstrained fn setup(with_authwits: bool) -> (TestEnvironment, AztecAddress, AztecAddress) {
let mut env = TestEnvironment::new();
let (owner, recipient) = if with_authwits {
(env.create_contract_account(), env.create_contract_account())
} else {
(env.create_light_account(), env.create_light_account())
};
// ... deploy contracts ...
(env, owner, recipient)
}
```
## Testing with authwits[](#testing-with-authwits "Direct link to Testing with authwits")
[Authwits](/developers/testnet/docs/aztec-nr/framework-description/authentication_witnesses.md) allow one account to authorize another to act on its behalf.
warning
Authwits require **contract accounts**, not light accounts.
### Import authwit helpers[](#import-authwit-helpers "Direct link to Import authwit helpers")
```
use aztec::test::helpers::authwit::{
add_private_authwit_from_call,
add_public_authwit_from_call,
};
```
### Private authwits[](#private-authwits "Direct link to Private authwits")
```
#[test]
unconstrained fn test_private_authwit() {
// Setup with contract accounts (required for authwits)
let (env, token_address, owner, spender) = setup(true);
// Create the call that needs authorization
let amount = 100;
let nonce = 7; // Non-zero nonce for authwit
let burn_call = Token::at(token_address).burn_private(owner, amount, nonce);
// Grant authorization from owner to spender
add_private_authwit_from_call(env, owner, spender, burn_call);
// Spender can now execute the authorized action
env.call_private(spender, burn_call);
}
```
### Public authwits[](#public-authwits "Direct link to Public authwits")
```
#[test]
unconstrained fn test_public_authwit() {
let (env, token_address, owner, spender) = setup(true);
// Create public action that needs authorization
let transfer_call = Token::at(token_address).transfer_in_public(owner, recipient, 100, nonce);
// Grant public authorization
add_public_authwit_from_call(env, owner, spender, transfer_call);
// Execute with authorization
env.call_public(spender, transfer_call);
}
```
## Time traveling[](#time-traveling "Direct link to Time traveling")
Contract calls do not advance the timestamp by default, despite each of them resulting in a block with a single transaction. Block timestamp can instead be manually manipulated by any of the following methods:
```
// Sets the timestamp of the next block to be mined, i.e. of the next public execution. Does not affect private execution.
env.set_next_block_timestamp(block_timestamp);
// Same as `set_next_block_timestamp`, but moving time forward by `duration` instead of advancing to a target timestamp.
env.advance_next_block_timestamp_by(duration);
// Mines an empty block at a given timestamp, causing the next public execution to occur at this time (like `set_next_block_timestamp`), but also allowing for private execution to happen using this empty block as the anchor block.
env.mine_block_at(block_timestamp);
```
## Testing failure cases[](#testing-failure-cases "Direct link to Testing failure cases")
Test functions that should fail using annotations:
### Generic failure[](#generic-failure "Direct link to Generic failure")
```
#[test(should_fail)]
unconstrained fn test_unauthorized_access() {
let (env, contract, owner) = setup(false);
let attacker = env.create_light_account();
// This should fail because attacker is not authorized
env.call_private(attacker, Contract::at(contract).owner_only_function());
}
```
### Specific error message[](#specific-error-message "Direct link to Specific error message")
```
#[test(should_fail_with = "Balance too low")]
unconstrained fn test_insufficient_balance() {
let (env, token, owner, recipient) = setup(false);
// Try to transfer more than available
let balance = 100;
let transfer_amount = 101;
env.call_private(owner, Token::at(token).transfer(recipient, transfer_amount));
}
```
### Testing authwit failures[](#testing-authwit-failures "Direct link to Testing authwit failures")
```
#[test(should_fail_with = "Unknown auth witness for message hash")]
unconstrained fn test_missing_authwit() {
let (env, token, owner, spender) = setup(true);
// Try to burn without authorization
let burn_call = Token::at(token).burn_private(owner, 100, 1);
// No authwit granted - this should fail
env.call_private(spender, burn_call);
}
```
## Test environment oracle versioning[](#test-environment-oracle-versioning "Direct link to Test environment oracle versioning")
The test environment uses an oracle interface to communicate between your Noir test code and the `aztec test` CLI. This interface is versioned so that mismatches between the Aztec.nr dependency used to compile the test and the CLI version are detected automatically.
The version uses two components, `major.minor`, with the same compatibility rules as [PXE oracle versioning](/developers/testnet/docs/foundational-topics/pxe.md#oracle-versioning):
* **`major`** must match exactly. A major bump means oracles were removed or had their signatures changed, and a test environment on a different major cannot safely run the test.
* **`minor`** indicates additive changes (new oracles). The test environment uses a best-effort approach: a test compiled against a higher `minor` is still allowed to run, and an error is only thrown if the test actually invokes an oracle the test environment does not know about.
### Resolving a version mismatch[](#resolving-a-version-mismatch "Direct link to Resolving a version mismatch")
If you see an error like *"Incompatible test environment version: The test was compiled with a newer version of Aztec.nr than your test environment supports"*, the test uses oracles from a newer Aztec.nr than your `aztec test` CLI supports.
To fix it, make sure y프로젝트로 돌아가기