Aztec 백서

Aztec

원문

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

n would normally route through the account // contract's entrypoint, whose is_valid check would prompt the user to sign. // With EmbeddedWallet, .simulate() runs kernelless with a stub-account // override applied to alice's account, so no signing prompt is triggered. const { result: decimals } = await tokenContract.methods .private_get_decimals() .simulate({ from: aliceAddress }); console.log("Token decimals (read via private view):", decimals); ``` > [Source code: docs/examples/ts/aztecjs\_kernelless\_simulation/index.ts#L44-L54](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_kernelless_simulation/index.ts#L44-L54) If you genuinely need to construct your own `SimulationOverrides` (for example, to combine a contract-instance swap with a `fastForwardContractUpdate` for upgrade testing), you can pass them through `.simulate()`: ``` import { SimulationOverrides } from "@aztec-labs/aztec.js/wallet"; const { result } = await contract.methods .transfer_in_private(sender, recipient, amount, nonce) .simulate({ from: sender, overrides: new SimulationOverrides({ /* contracts and/or publicStorage */ }), }); ``` The override map itself has to be built by code that knows the contract class id and live contract instance. That is normally the wallet, not the app. Note that `overrides` does not apply to [utility functions](/developers/testnet/docs/foundational-topics/pxe/kernelless_simulations.md#where-kernelless-does-not-apply), those are simulated through `wallet.executeUtility`, which rejects `SimulationOverrides`. If your wallet does not handle the override path for you and you are tempted to reimplement it in app code, read the next section instead. ### Implementing the override in a custom wallet[​](#implementing-the-override-in-a-custom-wallet "Direct link to Implementing the override in a custom wallet") `EmbeddedWallet` (`yarn-project/wallets/src/embedded/embedded_wallet.ts`, in `@aztec-labs/wallets`) is the canonical implementation of the override pattern and the reference any custom wallet should follow. The three pieces it wires up are: 1. **Register the stub contract class with the PXE at wallet startup.** Inside `initStubClasses`, `EmbeddedWallet` calls `pxe.registerContractClass` for each supported account type's stub artifact and caches the resulting class id by account type. 2. **Build an override map for every account in scope.** Inside `buildAccountOverrides`, it fetches the live contract instance for each scoped address and returns a `ContractOverrides` map that copies the instance with `currentContractClassId` rewritten to the stub class id. The map covers every account in scope, not only `from`. 3. **Use the stub entrypoint and pass the override to `pxe.simulateTx`.** Inside the overridden `simulateViaEntrypoint`, it constructs the `TxExecutionRequest` through the stub account's `DefaultAccountEntrypoint` (so the request is signed by the stub's empty-signature provider) and calls `pxe.simulateTx` with the resulting `SimulationOverrides`. The key constraints on this path: * `skipKernels` must be `true` to use `contracts` overrides. The PXE rejects the combination otherwise. `pxe.simulateTx` already defaults `skipKernels` to `true`. * The stub contract class must be registered with the PXE before you reference it in an override. * The override map must cover every scoped account, not only `from`. ## Collecting authwit requests[​](#collecting-authwit-requests "Direct link to Collecting authwit requests") A simulation with the stub override active will reach `#[authorize_once]` call sites in app and token contracts without prompting for signatures. Each such site emits a `CallAuthorizationRequest` as an offchain effect, which the wallet can collect and turn into a real authentication witness for the eventual `.send()`. The example below uses the canonical contract-mediated pattern: Alice calls `Crowdfunding.donate(amount)`, which internally calls `transfer_in_private(alice, crowdfunding, amount, 0)` with `msg_sender = crowdfunding`. The token's `#[authorize_once]` macro requires an authwit from Alice authorizing the crowdfunding contract. Because Alice is the transaction sender, her PXE already has her notes and nullifier key, so the simulation can run end-to-end against her own state without any cross-wallet state sharing. Run the simulation and filter the offchain effects by the `CallAuthorizationRequest` selector: simulate-and-collect-effects ``` // Alice calls Crowdfunding.donate(amount). Internally the contract calls // transfer_in_private(alice, crowdfunding, amount, 0) with msg_sender = // crowdfunding, so the token's #[authorize_once] macro requires an authwit // from Alice authorizing the crowdfunding contract. Alice is the sender, so // her PXE has her notes and nullifier key — no cross-wallet state sharing // is required. // With kernelless + stub override (default in EmbeddedWallet), the simulation // runs without prompting Alice to sign; the macro emits a // CallAuthorizationRequest as an offchain effect that the wallet can turn // into a real authwit before .send(). const donationAmount = 100n; const donateAction = crowdfundingContract.methods.donate(donationAmount); const { offchainEffects } = await donateAction.simulate({ from: aliceAddress, includeMetadata: true, }); // Filter offchain effects for authwit requests by selector. const authwitSelector = await CallAuthorizationRequest.getSelector(); const authwitEffects = offchainEffects.filter( (effect) => effect.data.length > 0 && effect.data[0].equals(authwitSelector.toField()), ); if (authwitEffects.length !== 1) { throw new Error( `Expected exactly one CallAuthorizationRequest, got ${authwitEffects.length}`, ); } ``` > [Source code: docs/examples/ts/aztecjs\_kernelless\_simulation/index.ts#L82-L114](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_kernelless_simulation/index.ts#L82-L114) Decode each effect into a `CallAuthorizationRequest`. The `innerHash` field is the piece the authorizing account needs to sign: decode-call-authorization ``` // Decode each effect into a CallAuthorizationRequest. The inner hash is the // piece the authorizing account (Alice) needs to sign. const authorizationRequests = await Promise.all( authwitEffects.map((effect) => CallAuthorizationRequest.fromFields(effect.data), ), ); for (const request of authorizationRequests) { console.log("Authwit needed:", { onBehalfOf: request.onBehalfOf.toString(), msgSender: request.msgSender.toString(), functionSelector: request.functionSelector.toString(), }); } if (!authorizationRequests[0].onBehalfOf.equals(aliceAddress)) { throw new Error( `Expected onBehalfOf to be alice (${aliceAddress.toString()}), got ${authorizationRequests[0].onBehalfOf.toString()}`, ); } ``` > [Source code: docs/examples/ts/aztecjs\_kernelless\_simulation/index.ts#L116-L138](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_kernelless_simulation/index.ts#L116-L138) Build a real authentication witness from each inner hash and send the transaction with the collected witnesses attached: build-authwits-and-send ``` // Alice creates a real authentication witness from each inner hash. The // `consumer` is the contract that consumes the authwit — here, the token, // because that's where the inner transfer_in_private (and its #[authorize_once] // site) runs. const authWitnesses = await Promise.all( authorizationRequests.map((request) => wallet.createAuthWit(request.onBehalfOf, { consumer: tokenContract.address, innerHash: request.innerHash, }), ), ); // Alice now sends the real donate transaction with the collected authwits // attached. // Note: EmbeddedWallet.sendTx already runs this pre-simulation + authwit // collection internally, so passing `authWitnesses` here is redundant for // EmbeddedWallet. We pass them explicitly anyway because this is the pattern // a wallet that does not auto-collect needs to follow. await donateAction.send({ from: aliceAddress, authWitnesses, }); ``` > [Source code: docs/examples/ts/aztecjs\_kernelless\_simulation/index.ts#L140-L165](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_kernelless_simulation/index.ts#L140-L165) The app does not need to know which calls require authwits ahead of time. The simulation discovers them; the wallet signs them at send time. `EmbeddedWallet.sendTx` runs this same simulate-then-collect flow internally before delegating to `BaseWallet.sendTx`, so an app that uses `EmbeddedWallet` does not need to call `.simulate()` manually and pass `authWitnesses` to `.send()`. The explicit pattern above is the one a wallet that does not auto-collect must implement, either inside its `sendTx` (as `EmbeddedWallet` does) or inside the app call site. ## Things to watch out for[​](#things-to-watch-out-for "Direct link to Things to watch out for") * **`AztecAddress.ZERO` is not "no sender".** Use `NO_FROM` (from `@aztec-labs/aztec.js/account`) for calls that genuinely have no account context, and a real account address otherwise. * **A private FPC needs to be included in fee options for accurate gas.** Kernelless simulation matches full simulation on gas, but only if the simulation sees the same fee path as the real transaction. If the user will pay through a fee payment contract (FPC) that emits private notes, pass that FPC in the simulation's fee options so its side effects are accounted for. Kernelless plus a private FPC is the supported path; you do not need a full simulation to get accurate gas. * **`profile()` is not kernelless.** If you call `.profile()` to count circuit gates, the kernels run regardless. Use `.simulate()` if you only need return values, offchain effects, or gas estimates. * **Utility functions reject overrides.** `FunctionType.UTILITY` calls go through `wallet.executeUtility`, and `ContractFunctionInteraction.simulate` throws `overrides are not supported for utility function simulation` if you pass non-empty `overrides.publicStorage` or `overrides.contracts`. Utility functions do not need an override anyway, since they do not run through an account contract. ## Related[​](#related "Direct link to Related") * [Kernelless simulations](/developers/testnet/docs/foundational-topics/pxe/kernelless_simulations.md) for the conceptual model. * [Reading contract data](/developers/testnet/docs/aztec-js/how_to_read_data.md) for the basic `.simulate()` API. * [Authentication witnesses](/developers/testnet/docs/foundational-topics/advanced/authwit.md) for what `CallAuthorizationRequest` represents. --- # Testing Smart Contracts This guide covers how to test Aztec smart contracts by connecting to a local network, deploying contracts, and verifying their behavior. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * A running [local Aztec network](/developers/testnet/getting_started_on_local_network.md) * A compiled contract artifact (see [How to compile a contract](/developers/testnet/docs/aztec-nr/compiling_contracts.md)) * Node.js test framework (Jest, Vitest, or similar) ## Setting up the test environment[​](#setting-up-the-test-environment "Direct link to Setting up the test environment") Connect to your local Aztec network and create an embedded wallet: connect\_to\_network ``` import { createAztecNodeClient, waitForNode } from "@aztec-labs/aztec.js/node"; import { EmbeddedWallet } from "@aztec-labs/wallets/embedded"; import { getInitialTestAccountsData } from "@aztec-labs/accounts/testing"; const nodeUrl = process.env.AZTEC_NODE_URL ?? "http://localhost:8080"; const node = createAztecNodeClient(nodeUrl); // Wait for the network to be ready await waitForNode(node); // Create an EmbeddedWallet connected to the node const wallet = await EmbeddedWallet.create(node, { ephemeral: true }); ``` > [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L1-L14](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L1-L14) The `EmbeddedWallet` manages accounts, tracks deployed contracts, and handles transaction proving. It connects to the Aztec node which provides access to both the Private eXecution Environment (PXE) and the network. ## Loading test accounts[​](#loading-test-accounts "Direct link to Loading test accounts") The local network comes with pre-funded accounts. Load them into your wallet: load\_test\_accounts ``` import { registerInitialLocalNetworkAccountsInWallet } from "@aztec-labs/wallets/testing"; // wallet is the EmbeddedWallet from the setup section above const [alice, bob] = await registerInitialLocalNetworkAccountsInWallet(wallet); ``` > [Source code: docs/examples/ts/aztecjs\_testing/index.ts#L117-L122](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_testing/index.ts#L117-L122) ## Deploying contracts in tests[​](#deploying-contracts-in-tests "Direct link to Deploying contracts in tests") Deploy contracts using the generated contract class: deploy\_test\_contract ``` // wallet is from the setup section; alice is from registerInitialLocalNetworkAccountsInWallet const { contract: testToken } = await TokenContract.deploy( wallet, alice, // admin "TestToken", "TST", 18, ).send({ from: alice }); ``` > [Source code: docs/examples/ts/aztecjs\_testing/index.ts#L124-L133](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_testing/index.ts#L124-L133) ## Verifying contract state[​](#verifying-contract-state "Direct link to Verifying contract state") Use `.simulate()` to read contract state without creating a transaction: 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) Simulations are free (no gas cost) and return the function's result directly. Use them for: * Checking balances and state before/after transactions * Validating expected outcomes in assertions * Debugging contract behavior ## Sending test transactions[​](#sending-test-transactions "Direct link to Sending test transactions") Send transactions and wait for confirmation: send\_transaction ``` const { receipt } = await token.methods .mint_to_public(aliceAddress, 1000n) .send({ from: aliceAddress }); console.log(`Transaction mined in block ${receipt.blockNumber}`); console.log(`Transaction fee: ${receipt.transactionFee}`); ``` > [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L142-L149](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L142-L149) The `send()` method returns when the transaction is included in a block. ## Example test structure[​](#example-test-structure "Direct link to Example test structure") Here's a complete test example showing the typical structure with setup, test cases, and assertions: complete\_test\_example ``` import { createAztecNodeClient, waitForNode } from "@aztec-labs/aztec.js/node"; import { EmbeddedWallet } from "@aztec-labs/wallets/embedded"; import { getInitialTestAccountsData } from "@aztec-labs/accounts/testing"; import { TokenContract } from "@aztec-labs/noir-contracts.js/Token"; import { AztecAddress } from "@aztec-labs/aztec.js/addresses"; // This file demonstrates a complete Jest test structure. // In a real test file, wrap this in describe() and it() blocks. // Test setup variables let wallet: EmbeddedWallet; let aliceAddress: AztecAddress; let bobAddress: AztecAddress; let token: TokenContract; // beforeAll equivalent - setup async function setup() { const node = createAztecNodeClient( process.env.AZTEC_NODE_URL ?? "http://localhost:8080", ); await waitForNode(node); wallet = await EmbeddedWallet.create(node, { ephemeral: true }); const testAccounts = await getInitialTestAccountsData(); [aliceAddress, bobAddress] = await Promise.all( testAccounts.slice(0, 2).map(async (account) => { return ( await wallet.createSchnorrInitializerlessAccount( account.secret, account.salt, account.signingKey, ) ).address; }), ); ({ contract: token } = await TokenContract.deploy( wallet, aliceAddress, "Test", "TST", 18, ).send({ from: aliceAddress, })); } // Test: mints tokens to an account async function testMintTokens() { await token.methods .mint_to_public(aliceAddress, 1000n) .send({ from: aliceAddress }); const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); if (balance !== 1000n) { throw new Error(`Expected balance 1000n, got ${balance}`); } console.log("✓ Mint tokens test passed"); } // Test: transfers tokens between accounts async function testTransferTokens() { // First mint some tokens await token.methods .mint_to_public(aliceAddress, 1000n) .send({ from: aliceAddress }); // Transfer to bob using public transfer await token.methods .transfer_in_public(aliceAddress, bobAddress, 100n, 0n) .send({ from: aliceAddress }); const { result: aliceBalance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); const { result: bobBalance } = await token.methods .balance_of_public(bobAddress) .simulate({ from: bobAddress }); // Note: balances accumulate from previous test console.log(`Alice balance: ${aliceBalance}, Bob balance: ${bobBalance}`); console.log("✓ Transfer tokens test passed"); } // Test: reverts when transferring more than balance async function testRevertOnOverTransfer() { const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); try { await token.methods .transfer_in_public(aliceAddress, bobAddress, balance + 1n, 0n) .simulate({ from: aliceAddress }); throw new Error("Expected simulation to throw"); } catch (error) { // Expected to throw console.log("✓ Revert on over-transfer test passed"); } } // Run all tests async function runTests() { await setup(); await testMintTokens(); await testTransferTokens(); await testRevertOnOverTransfer(); console.log("\n✓ All tests passed"); } await runTests(); ``` > [Source code: docs/examples/ts/aztecjs\_testing/index.ts#L1-L115](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_testing/index.ts#L1-L115) ## Testing failure cases[​](#testing-failure-cases "Direct link to Testing failure cases") Test that invalid operations revert as expected: test\_revert\_case ``` async function testRevertExample() { // testToken and alice are from the deploy/load sections above const { result: balance } = await testToken.methods .balance_of_public(alice) .simulate({ from: alice }); let reverted = false; try { await testToken.methods .transfer_in_public(alice, bob, balance + 1n, 0n) .simulate({ from: alice }); } catch (error) { reverted = true; } if (!reverted) { throw new Error("Expected simulation to revert for over-transfer"); } console.log("✓ Revert on over-transfer test passed"); } await testRevertExample(); ``` > [Source code: docs/examples/ts/aztecjs\_testing/index.ts#L135-L158](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_testing/index.ts#L135-L158) Use `.simulate()` to test reverts without spending gas. The simulation will throw if the transaction would fail onchain. ## Simulating with overrides[​](#simulating-with-overrides "Direct link to Simulating with overrides") `.simulate()` accept
프로젝트로 돌아가기