### Install Aztec CLI and Set Version Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Installs the Aztec CLI tools and sets the compatible version for all examples. Ensure nargo is available after installation. ```bash # Install Aztec CLI bash -i <(curl -s https://install.aztec.network) # Set compatible version aztec-up 4.2.0-aztecnr-rc.2 # Verify nargo is available (bundled with Aztec CLI) ~/.aztec/current/bin/nargo --version # nargo version = 1.0.0-beta.18 ``` -------------------------------- ### Start Development Server Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Start the Vite development server for the web app. ```bash yarn dev ``` -------------------------------- ### Complete Workflow Commands Source: https://github.com/aztecprotocol/aztec-examples/blob/next/note-send-proof/readme.md A sequence of commands for a fresh setup, including dependency installation, Aztec version setup, contract compilation, starting the local network, and running tests. ```bash # 1. Install dependencies yarn install # 2. Setup Aztec aztec-up 4.2.0-aztecnr-rc.2 # 3. Compile contract and generate TypeScript bindings yarn ccc # 4. Start local network (in a new terminal) aztec start --local-network # 5. Run tests (in original terminal) yarn test ``` -------------------------------- ### Complete Workflow Commands Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md A sequence of commands for a fresh setup, including dependency installation, Aztec setup, circuit and contract compilation, proof generation, local network startup, and deployment/verification. ```bash # 1. Install dependencies yarn install # 2. Setup Aztec aztec-up 4.2.0-aztecnr-rc.2 # 3. Verify nargo is available (bundled with Aztec CLI) ~/.aztec/current/bin/nargo --version # 4. Compile circuit cd circuit && nargo compile && cd .. # 5. Compile contract yarn ccc # 6. Generate proof data yarn data # 7. Start local network (in a new terminal) aztec start --local-network # 8. Deploy and verify (in original terminal) yarn recursion ``` -------------------------------- ### Start Aztec Sandbox Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Start the Aztec sandbox instance. Ensure it is running on http://localhost:8080 before starting the development server. ```bash aztec start --sandbox ``` -------------------------------- ### Install Aztec Tools Source: https://github.com/aztecprotocol/aztec-examples/blob/next/README.md Installs the Aztec CLI and essential tools. Use `aztec-up` to set a specific version if needed. ```bash # Install the Aztec CLI and tools bash -i <(curl -s https://install.aztec.network) # Set specific Aztec version (if needed) aztec-up 4.2.0-aztecnr-rc.2 ``` -------------------------------- ### Start Testing Execution Environment (TXE) Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Manually starts the TXE on a specified port for debugging test execution. ```bash aztec start --txe --port=8081 ``` -------------------------------- ### Build and Run Starter Token Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Commands to build the contract and run the TypeScript client for the starter token example. ```bash # Navigate to reference implementation cd starter-token/reference # Build the contract cd contract && aztec compile && cd .. # Build and run TypeScript client cd ts npm install npm run build npm start ``` -------------------------------- ### Create Vite Project and Install Dependencies Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Create a new React TypeScript project using Vite and install initial dependencies. ```bash yarn create vite testwallet-webapp-tutorial-new --template react-ts cd testwallet-webapp-tutorial-new yarn install ``` -------------------------------- ### Run Recursive Verification Tests Source: https://github.com/aztecprotocol/aztec-examples/blob/next/README.md Executes the test suite for the Recursive Verification example. Navigate to the example directory first. ```bash # Recursive Verification tests cd recursive_verification bun test ``` -------------------------------- ### Install Aztec CLI Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Installs the Aztec CLI. This command requires bash and curl. ```bash bash -i <(curl -s https://install.aztec.network) ``` -------------------------------- ### Start Aztec Local Network Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Starts the local development environment for Aztec. Use '--local-network' for a full network or '--sandbox' for a mode with test accounts. ```bash # Start full local network (node + PXE) aztec start --local-network # Network runs at http://localhost:8080 # For sandbox mode (includes test accounts) aztec start --sandbox ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Installs project dependencies using Yarn. Ensure Node.js v22+ and Yarn are installed. ```bash yarn install ``` -------------------------------- ### Development Prerequisites Source: https://github.com/aztecprotocol/aztec-examples/blob/next/prediction-market/README.md Commands to install the necessary Aztec development tools and project dependencies. ```bash # Install Aztec tools bash -i <(curl -s https://install.aztec.network) aztec-up 4.2.0-aztecnr-rc.2 # Install dependencies yarn install ``` -------------------------------- ### Install Dependencies and Aztec Tools Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/CLAUDE.md Installs project dependencies and updates Aztec CLI tools. Ensure the Aztec local network is running for contract deployment. ```bash yarn install aztec-up aztec start --local-network ``` -------------------------------- ### Set Aztec version Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Use this command to align the local environment with the version requirements of a specific example. ```bash aztec-up ``` -------------------------------- ### Start Local Aztec Network without PXE Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Starts the local Aztec network without the PXE. Useful when using aztec-wallet. ```bash NO_PXE=true aztec start --local-network ``` -------------------------------- ### Run Recursive Verification Integration Tests Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Navigates to the recursive verification example directory and runs its integration tests using yarn. ```bash cd recursive_verification yarn test ``` -------------------------------- ### Install Vite Build Tooling Dependencies Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Install development dependencies for Vite, including Node.js polyfills and type definitions. ```bash yarn add -D vite-plugin-node-polyfills @types/node ``` -------------------------------- ### Start Aztec Local Network Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Ensure the Aztec local network is running before proceeding with tests. ```bash aztec start --local-network ``` -------------------------------- ### Configure Aztec Contract Dependencies Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Example Nargo.toml configuration for Aztec contract dependencies. ```toml [dependencies] aztec = { git = "https://github.com/AztecProtocol/aztec-packages/", tag = "vX.X.X", directory = "noir-projects/aztec-nr/aztec" } easy_private_state = { git = "https://github.com/AztecProtocol/aztec-packages/", tag = "vX.X.X", directory = "noir-projects/aztec-nr/easy-private-state" } ``` -------------------------------- ### Install Aztec Dependencies Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Add the required Aztec SDK packages to your project. Ensure the version matches the project's compatibility requirements. ```bash yarn add @aztec/accounts@4.2.0-aztecnr-rc.2 \ @aztec/aztec.js@4.2.0-aztecnr-rc.2 \ @aztec/wallets@4.2.0-aztecnr-rc.2 \ @aztec/noir-contracts.js@4.2.0-aztecnr-rc.2 ``` -------------------------------- ### Check Nargo Version Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Verifies the installed Nargo version, which is bundled with the Aztec CLI. Nargo is used for vanilla Noir circuits. ```bash ~/.aztec/current/bin/nargo --version ``` -------------------------------- ### Run Aztec Tests Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Executes the test suite for Aztec contracts. This command automatically starts the TXE (Test Execution Environment). ```bash aztec test ``` -------------------------------- ### Deploy Contract and Verify Proof Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Connects to the Aztec PXE, deploys the `ValueNotEqual` contract, submits the proof from `data.json` for verification, and increments a counter if verification succeeds. ```bash yarn recursion ``` -------------------------------- ### Run All Project Tests Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Execute the comprehensive test suite for contract deployment and proof verification. Use watch mode for development or run the full suite locally, which includes compilation. ```bash yarn test ``` ```bash yarn test:watch ``` ```bash ./run-tests.sh ``` -------------------------------- ### Building the Contract Source: https://github.com/aztecprotocol/aztec-examples/blob/next/prediction-market/README.md Commands to compile the contract and generate TypeScript bindings. ```bash # Compile the contract aztec compile # Generate TypeScript bindings aztec codegen target -o artifacts ``` -------------------------------- ### Run Tests Source: https://github.com/aztecprotocol/aztec-examples/blob/next/note-send-proof/readme.md Executes the project's test suite, which includes contract deployment, note creation with fixed randomness, and verification of computed note hashes against on-chain hashes. ```bash yarn test ``` -------------------------------- ### Deploy Contract and Run Proof Verification Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/CLAUDE.md Deploys the ValueNotEqual contract to the Aztec network and executes the `increment` function, which verifies the generated Noir proof on-chain. Requires a running local network. ```bash yarn recursion # This runs: tsx scripts/run_recursion.ts ``` -------------------------------- ### Test Aztec Contracts Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Example of a test function using the Testing Execution Environment (TXE) in Noir. ```noir use dep::aztec::test::helpers::test_environment::TestEnvironment; #[test] unconstrained fn test_function() { let mut env = TestEnvironment::new(); let user = env.create_account_contract(1); env.impersonate(user); // Deploy and interact with contracts let contract = env.deploy_self("ContractName").without_initializer(); // Test contract functions } ``` -------------------------------- ### Deploy Password Account Contract with TypeScript Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Demonstrates the deployment process for the password-based account contract using the Aztec SDK and registering it with an AccountManager. ```typescript import { Fr } from '@aztec/aztec.js/fields'; import { EmbeddedWallet } from '@aztec/wallets/embedded'; import { AccountManager, DeployMethod, Contract } from '@aztec/aztec.js'; import { PasswordAccountContract } from './password-account-entrypoint'; // Create password account contract with password const passwordAccountContract = new PasswordAccountContract(new Fr(123123123123)); const artifact = await passwordAccountContract.getContractArtifact(); const { constructorName, constructorArgs } = await passwordAccountContract.getInitializationFunctionAndArgs(); // Setup wallet const wallet = await EmbeddedWallet.create( createAztecNodeClient('http://localhost:8080'), { ephemeral: true } ); // Deploy the contract const accountContractDeployMethod = new DeployMethod( publicKeys, wallet, artifact, (instance, wallet) => Contract.at(instance.address, artifact, wallet), constructorArgs, constructorName, ); const { contract: deployedAccountContract } = await accountContractDeployMethod.send(deployAccountOpts); console.log('PasswordAccount deployed at:', deployedAccountContract.address); // Register account with manager const accountManager = await AccountManager.create( wallet, Fr.random(), passwordAccountContract, Fr.random() ); console.log('Account registered at:', accountManager.address.toString()); ``` -------------------------------- ### Clean Rebuild Project Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Remove generated files and rebuild the project from scratch. This includes compiling the circuit, generating contract artifacts, and creating proof data. ```bash rm -rf circuit/target contract/target contract/artifacts data.json cd circuit && nargo compile && cd .. yarn ccc yarn data ``` -------------------------------- ### View Project Structure Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Standard directory layout for an Aztec-compatible web application. ```text test-wallet-webapp/ ├── src/ │ ├── App.tsx # Main application component │ ├── main.tsx # Application entry point │ ├── consoleInterceptor.ts # Console output capture utility │ └── ... ├── vite.config.ts # Vite configuration with Aztec compatibility ├── package.json # Dependencies └── README.md # This file ``` -------------------------------- ### Deploy Contract and Verify Proof On-Chain Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Deploys the ValueNotEqual contract and submits proof data for on-chain verification using the Aztec SDK. ```typescript import { createAztecNodeClient } from "@aztec/aztec.js/node"; import { SponsoredFeePaymentMethod } from "@aztec/aztec.js/fee"; import { EmbeddedWallet } from "@aztec/wallets/embedded"; import { NO_FROM } from "@aztec/aztec.js/account"; import { Fr } from "@aztec/aztec.js/fields"; import { ValueNotEqualContract } from "../contract/artifacts/ValueNotEqual"; import data from "../data.json"; const NODE_URL = "http://localhost:8080"; // Setup wallet with sponsored fees const aztecNode = await createAztecNodeClient(NODE_URL); const wallet = await EmbeddedWallet.create(aztecNode, { ephemeral: true }); // Create and deploy account const account = await wallet.createSchnorrAccount(Fr.random(), Fr.random()); const manager = await account.getDeployMethod(); await manager.send({ from: NO_FROM, fee: { paymentMethod: sponsoredPaymentMethod }, }); const accounts = await wallet.getAccounts(); // Deploy ValueNotEqual contract const { contract: valueNotEqual } = await ValueNotEqualContract.deploy( wallet, 10, // initial counter value accounts[0].item, data.vkHash ) .send({ from: accounts[0].item, fee: { paymentMethod: sponsoredPaymentMethod }, }); console.log(`Contract deployed at: ${valueNotEqual.address}`); // Verify proof and increment counter await valueNotEqual.methods.increment( accounts[0].item, data.vkAsFields, data.proofAsFields, data.publicInputs, ).send({ from: accounts[0].item, fee: { paymentMethod: sponsoredPaymentMethod }, }); // Read counter value const counterValue = (await valueNotEqual.methods .get_counter(accounts[0].item) .simulate({ from: accounts[0].item })).result; console.log(`Counter value: ${counterValue}`); // Output: Counter value: 11 ``` -------------------------------- ### Compile Aztec Contract Source: https://github.com/aztecprotocol/aztec-examples/blob/next/custom-note/README.md Use the Aztec CLI to compile your Noir smart contract. ```bash aztec compile ``` -------------------------------- ### Main Contract Implementation Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md This file, src/main.nr, contains the main implementation of the Noir contract. ```rust src/main.nr ``` -------------------------------- ### Run Full Test Suite with Compilation Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Executes a local test runner script that likely includes compilation and testing steps. ```bash ./run-tests.sh ``` -------------------------------- ### Run All Tests Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Execute all tests in the test suite. ```bash bun test ``` -------------------------------- ### Generate Proof Data Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Generate proof data, which will create a data.json file. ```bash bun data ``` -------------------------------- ### Noir Project Configuration Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md This file, Nargo.toml, contains the Noir project configuration, including dependencies. ```toml Nargo.toml ``` -------------------------------- ### Run Recursion Script for Contract Interaction Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/CLAUDE.md TypeScript script to deploy the ValueNotEqual contract, interact with it by calling the `increment` function with generated proof data, and verify the proof on-chain. Connects to the Aztec PXE at localhost:8080. ```typescript import { Fr, Point } from '@aztec/foundation/fields'; import { AztecNodeClient, PXE } from '@aztec/aztec-node'; import { AztecAddress, Contract, ContractDeploymentInfo, Wallet } from '@aztec/aztec.js'; import { completePartial, encodeArguments, NoirFunction, NoirFunctionType, PXEConfig } from '@aztec/types'; import { generate_proof, verify_proof } from '@aztec/bb.js'; import * as fs from 'fs'; const PXE_URL = 'http://localhost:8080'; async function run_recursion() { // Initialize PXE client const pxe = new PXE(new AztecNodeClient(PXE_URL)); const wallet = pxe.getWallet(); // Deploy contract const contract_artifact = JSON.parse(fs.readFileSync('./contract/target/ValueNotEqual.json', 'utf-8')); const deployment_info: ContractDeploymentInfo = await Contract.deploy(wallet, contract_artifact).send().deployed(); const contract_address = deployment_info.address; console.log(`Contract deployed to ${contract_address}`); // Load proof data const data = JSON.parse(fs.readFileSync('./scripts/data.json', 'utf-8')); const proof = new Uint8Array(data.proof); const public_inputs = new Fr(data.public_inputs[0]); // Assuming single public input const vk = new Uint8Array(data.vk); // Call increment function with proof const contract = await Contract.at(contract_address, contract_artifact, wallet); await contract.methods.increment(public_inputs.toString(), public_inputs.toString(), proof, vk).send().wait(); console.log('Increment function called with proof verification.'); // Get counter value const counter = await contract.methods.get_counter(wallet.getAddress().toString()).view(); console.log(`Counter for ${wallet.getAddress()}: ${counter}`); } run_recursion().catch((err) => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Connect to Aztec Node Client Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Initialize an Aztec node client and an embedded wallet to interact with the network. ```typescript import { createAztecNodeClient } from '@aztec/aztec.js/node' import { EmbeddedWallet } from '@aztec/wallets/embedded'; const nodeURL = 'http://localhost:8080'; const aztecNode = await createAztecNodeClient(nodeURL); const wallet = await EmbeddedWallet.create(aztecNode); ``` -------------------------------- ### Compile and Execute Noir Circuit Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/CLAUDE.md Commands for compiling, executing (generating witness), and testing Noir circuits using `nargo`. Navigate to the circuit directory before running. ```bash cd circuit && nargo compile cd circuit && nargo execute cd circuit && nargo test ``` -------------------------------- ### Deploy and Interact with Aztec Contract Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/EXPLAINER.md Connects to the Aztec network, deploys a contract with initial state, and submits a proof for verification via contract methods. ```typescript // 1. Connect to Aztec network and setup wallet const aztecNode = await createAztecNodeClient("http://localhost:8080"); const wallet = await EmbeddedWallet.create(aztecNode, { ephemeral: true }); // 2. Deploy the contract with initial counter = 10 and VK hash const contract = await ValueNotEqualContract.deploy( testWallet, 10, // Initial counter value accounts[0].item, // Owner address data.vkHash // VK hash stored in contract ) .send(sendOpts) .deployed(); // 3. Submit proof for verification (VK hash read from storage) const tx = await contract.methods .increment( accounts[0].item, data.vkAsFields, // Verification key data.proofAsFields, // The proof data.publicInputs // Public input (y=2) ) .send(sendOpts) .wait(); // 4. Check the counter increased const counter = await contract.methods .get_counter(accounts[0].item) .simulate({ from: accounts[0].item }); // Counter is now 11 (10 + 1) ``` -------------------------------- ### Implement Deterministic Note Hashing in Noir Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Demonstrates creating private notes with fixed randomness for reproducible hash verification. Uses a global constant for randomness. ```noir #[aztec] pub contract GettingStarted { use aztec::{ state_vars::PublicMutable, macros::{functions::{initializer, external}, storage::storage}, protocol::address::AztecAddress, }; use uint_note::uint_note::{UintNote, create_note_with_randomness}; // Fixed randomness for reproducible hash computation global NOTE_RANDOMNESS: Field = 6969; #[storage] struct Storage { owner: PublicMutable, } #[initializer] #[external("public")] fn setup(owner: AztecAddress) { self.storage.owner.write(owner); } /// Creates a private note with fixed randomness for hash verification #[external("private")] fn create_note_for_user(value: u128) { let note_owner = self.msg_sender(); let note = UintNote::new(value); create_note_with_randomness( self.context, note_owner, 1, // storage_slot note, NOTE_RANDOMNESS, ); } } ``` -------------------------------- ### Integrate Browser Wallet with Aztec.js Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Connects to an Aztec node, initializes an embedded wallet, and deploys a contract using TypeScript. Requires proper Vite configuration for the environment. ```typescript import { createAztecNodeClient } from '@aztec/aztec.js/node' import { getInitialTestAccountsData } from '@aztec/accounts/testing'; import { EmbeddedWallet } from '@aztec/wallets/embedded'; import { PrivateVotingContract } from '@aztec/noir-contracts.js/PrivateVoting'; import { AztecAddress } from '@aztec/aztec.js/addresses' // Connect to Aztec node const nodeURL = 'http://localhost:8080'; const aztecNode = await createAztecNodeClient(nodeURL); const wallet = await EmbeddedWallet.create(aztecNode); // Create Schnorr account from test data const [accountData] = await getInitialTestAccountsData(); const accountManager = await wallet.createSchnorrAccount( accountData.secret, accountData.salt, accountData.signingKey ); const accountAddress = accountManager.address; console.log('Wallet created:', accountAddress.toString()); // Deploy contract const { contract: deployedContract } = await PrivateVotingContract.deploy( wallet, accountAddress, ).send({ from: accountAddress }); console.log('Contract deployed at:', deployedContract.address.toString()); // Interact with contract const contract = await PrivateVotingContract.at(deployedContract.address, wallet); await contract.methods.cast_vote({ id: 1n }, 1n).send({ from: accountAddress }); console.log('Vote cast successfully!'); ``` -------------------------------- ### Compile Noir Circuit Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Compile the Noir circuit to generate necessary proof data. ```bash cd ../circuit && aztec-nargo compile && cd .. ``` -------------------------------- ### Compile Vanilla Noir Circuit Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Compiles a Noir circuit using the nargo compiler. Ensure the correct nargo version is on your PATH. ```bash nargo compile ``` -------------------------------- ### Configure Vite for Aztec SDK Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Sets up necessary polyfills and headers for WASM and Node.js compatibility in browser environments. ```typescript import { defineConfig, searchForWorkspaceRoot } from 'vite' import react from '@vitejs/plugin-react' import { nodePolyfills } from "vite-plugin-node-polyfills"; const nodeModulesPath = `${searchForWorkspaceRoot(process.cwd())}/node_modules`; // Workaround for polyfills module resolution const nodePolyfillsFix = (options) => ({ ...nodePolyfills(options), resolveId(source) { const m = /^vite-plugin-node-polyfills\/shims\/(buffer|global|process)$/.exec(source); if (m) { return `${nodeModulesPath}/vite-plugin-node-polyfills/shims/${m[1]}/dist/index.cjs`; } }, }); export default defineConfig({ server: { // Required headers for WASM multithreading headers: { "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "require-corp", }, }, plugins: [ react(), nodePolyfillsFix({ include: ["buffer", "path", "process", "net", "tty"], }), ], optimizeDeps: { include: ['pino', 'pino/browser'], exclude: ['@aztec/noir-noirc_abi', '@aztec/noir-acvm_js', '@aztec/bb.js', '@aztec/noir-noir_js'] }, }) ``` -------------------------------- ### Check Contract Compilation Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Verify that the contracts have been compiled and artifacts exist. ```bash ls ../contract/artifacts/ ``` -------------------------------- ### Check Proof Data Existence Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Verify that the proof data file (data.json) has been generated. ```bash ls ../data.json ``` -------------------------------- ### Run All Tests with CI Environment Source: https://github.com/aztecprotocol/aztec-examples/blob/next/README.md Executes all tests in a manner similar to the Continuous Integration environment. ```bash # Run with CI-like environment ./run-tests.sh ``` -------------------------------- ### Compile Contract and Generate Bindings Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Compile the contract and generate TypeScript bindings for interacting with it. ```bash bun ccc ``` -------------------------------- ### Run Nargo Tests with TXE Output Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Runs nargo tests, connecting to a running TXE for oracle resolution and displaying detailed output. ```bash nargo test --oracle-resolver http://127.0.0.1:8081 --show-output ``` -------------------------------- ### Import Test Accounts to Aztec Wallet Source: https://github.com/aztecprotocol/aztec-examples/blob/next/CLAUDE.md Imports pre-defined test accounts into the aztec-wallet for easy interaction. ```bash aztec-wallet import-test-accounts ``` -------------------------------- ### Interact with Contracts via CLI Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Common CLI commands for deploying, calling, simulating, and profiling Aztec contracts. ```bash # Import test accounts to aztec-wallet aztec-wallet import-test-accounts # Deploy a contract (without constructor) aztec-wallet deploy --no-init target/contract.json --from test0 --alias mycontract # Call a contract function aztec-wallet send increment --args 0x123 --contract-address mycontract -f test0 # Simulate a function call (read-only) aztec-wallet simulate get_counter --args 0x123 --contract-address mycontract -f test0 # Profile gas/gates for a function aztec-wallet profile increment --args 0x123 --contract-address mycontract -f test0 ``` -------------------------------- ### Interact with Prediction Market via TypeScript Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Demonstrates how to perform private deposits, execute private bets, and query market data using the Aztec TypeScript SDK. ```typescript // Deposit collateral privately await market.methods.deposit(1000n).send({ from: myAddress }).wait() // Buy YES outcome privately - single transaction with partial notes await market.methods.buy_outcome( true, // is_yes 500n, // collateral_amount 900n, // min_shares_out (slippage protection) ).send({ from: myAddress }).wait() // Check private balance (only visible to owner) const myYesBalance = await market.methods.get_yes_balance(myAddress) .simulate({ from: myAddress }) // Get public market price const yesPrice = await market.methods.get_price(true).simulate() console.log(`YES price: ${yesPrice / 1_000_000}%`) ``` -------------------------------- ### Compile and Test Aztec Contracts Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Commands for compiling contracts, generating bindings, and running tests using the Testing Execution Environment (TXE). ```bash # Compile Aztec contract (includes post-processing) aztec compile # Generate TypeScript bindings aztec codegen target -o artifacts # Run contract tests with TXE aztec test # Or manually with TXE for debug output: # Terminal 1: Start Testing Execution Environment aztec start --txe --port=8081 # Terminal 2: Run tests with output nargo test --oracle-resolver http://127.0.0.1:8081 --show-output # Compile vanilla Noir circuit cd circuit && nargo compile # Execute circuit to generate witness nargo execute ``` -------------------------------- ### Set Aztec Version Source: https://github.com/aztecprotocol/aztec-examples/blob/next/custom-note/README.md Use the aztec-up tool to set the required Aztec version for the project. ```bash aztec-up 4.2.0-aztecnr-rc.2 ``` -------------------------------- ### Deploy Password Account Contract Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md Deploys the password account contract to the local Aztec network using TypeScript. ```bash npx tsx deploy-account-contract.ts ``` -------------------------------- ### Recursive Proof Verification Contract (Noir) Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Demonstrates verifying Noir circuit proofs within Aztec smart contracts using the UltraHonk proving system. It stores a verification key hash and verifies proofs in private functions before updating public state. ```noir use aztec::macros::aztec; #[aztec] pub contract ValueNotEqual { use aztec::{ macros::{functions::{external, initializer, only_self, view}, storage::storage}, protocol::{address::AztecAddress, traits::ToField}, state_vars::{Map, PublicImmutable, PublicMutable}, }; use bb_proof_verification::{UltraHonkVerificationKey, UltraHonkZKProof, verify_honk_proof}; #[storage] struct Storage { counters: Map, Context>, vk_hash: PublicImmutable, } #[initializer] #[external("public")] fn constructor(headstart: Field, owner: AztecAddress, vk_hash: Field) { self.storage.counters.at(owner).write(headstart); self.storage.vk_hash.initialize(vk_hash); } #[external("private")] fn increment( owner: AztecAddress, verification_key: UltraHonkVerificationKey, proof: UltraHonkZKProof, public_inputs: [Field; 1], ) { let vk_hash = self.storage.vk_hash.read(); verify_honk_proof(verification_key, proof, public_inputs, vk_hash); self.enqueue_self._increment_public(owner); } #[only_self] #[external("public")] fn _increment_public(owner: AztecAddress) { let current = self.storage.counters.at(owner).read(); self.storage.counters.at(owner).write(current + 1); } #[view] #[external("public")] fn get_counter(owner: AztecAddress) -> Field { self.storage.counters.at(owner).read() } } ``` -------------------------------- ### Testing the Contract Source: https://github.com/aztecprotocol/aztec-examples/blob/next/prediction-market/README.md Commands for running Noir unit tests and end-to-end tests. ```bash aztec test ``` ```bash # Start Aztec sandbox (in separate terminal) aztec start --sandbox # Run tests yarn test ``` -------------------------------- ### Compile Aztec Contract Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Compiles the Aztec smart contract, post-processes it for deployment, and generates TypeScript bindings in `contract/artifacts/`. ```bash yarn ccc ``` -------------------------------- ### Account Action Handlers Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md This file, src/account_actions.nr, defines the handlers for account-specific actions. ```rust src/account_actions.nr ``` -------------------------------- ### Run Specific Test File Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/tests/README.md Execute tests from a particular test file. ```bash bun test recursive_verification.test.ts ``` -------------------------------- ### Password Account Entrypoint Implementation Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md This TypeScript file, ts/password-account-entrypoint.ts, implements the password-based account entrypoint. ```typescript ts/password-account-entrypoint.ts ``` -------------------------------- ### Collateral Management Source: https://github.com/aztecprotocol/aztec-examples/blob/next/prediction-market/README.md Shows how to manage private collateral balances including deposits, withdrawals, and balance checks. ```typescript // Deposit collateral (private) await market.methods.deposit(1000n).send({ from: myAddress }).wait() // Withdraw collateral (private) await market.methods.withdraw(500n).send({ from: myAddress }).wait() // Check balance (view private notes) const balance = await market.methods.get_collateral_balance(myAddress).simulate({ from: myAddress }) ``` -------------------------------- ### Generate Proof Data Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Generates the verification key, UltraHonk proof, and public inputs using `scripts/generate_data.ts`. The proof data is saved to `data.json`. ```bash yarn data ``` -------------------------------- ### Construct Transaction with Password Account Entrypoint (TypeScript) Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md Handles transaction construction with custom entrypoint parameters for the password account. Requires contract address, authentication details, password, chain ID, and version. ```typescript const entrypoint = new PasswordAccountEntrypoint( address, auth, password, chainId, version ); ``` -------------------------------- ### Deployment Script Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md This TypeScript file, ts/deploy-account-contract.ts, contains the script for deploying the account contract. ```typescript ts/deploy-account-contract.ts ``` -------------------------------- ### Compile Noir Circuit Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Compiles the Noir circuit located in `circuit/src/main.nr`. This generates the circuit bytecode in `target/hello_circuit.json`. ```bash cd circuit && nargo compile ``` -------------------------------- ### Execute Noir Circuit Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Executes the compiled Noir circuit with default inputs defined in `circuit/Prover.toml`. Generates a witness for testing. ```bash cd circuit && nargo execute ``` -------------------------------- ### Betting Flow (Single Transaction) Source: https://github.com/aztecprotocol/aztec-examples/blob/next/prediction-market/README.md Demonstrates the process of depositing collateral and executing a private bet in a single transaction. ```typescript // Deposit collateral privately await market.methods.deposit(1000n).send({ from: myAddress }).wait() // Buy outcome privately - single transaction! await market.methods.buy_outcome( true, // is_yes 500n, // collateral_amount 900n, // min_shares_out (slippage protection) ).send({ from: myAddress }).wait() // Your shares are immediately in your private balance! const myBalance = await market.methods.get_yes_balance(myAddress).simulate({ from: myAddress }) ``` -------------------------------- ### View Custom Notes Source: https://github.com/aztecprotocol/aztec-examples/blob/next/custom-note/README.md An unconstrained utility function to query all custom notes for a specified owner. This call does not consume gas. ```rust CustomNote.view_custom_notes(owner_address) ``` -------------------------------- ### Create Password Account Interface (TypeScript) Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md Provides the account interface for creating transactions using the password account. Requires an authWitnessProvider, contract address, chain info, and the password. ```typescript const accountInterface = new PasswordAccountInterface( authWitnessProvider, address, chainInfo, password ); ``` -------------------------------- ### Define Aztec Smart Contract Interface Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/EXPLAINER.md Outlines the contract functions for initializing state, verifying proofs, and querying the counter. The increment function requires the verification key, proof data, and public inputs. ```rust // 1. Initialize with a starting counter value and VK hash fn constructor(headstart: Field, owner: AztecAddress, vk_hash: Field) // 2. Verify proof (VK hash read from storage) and increment counter fn increment( owner: AztecAddress, verification_key: [Field; 115], proof: [Field; 508], public_inputs: [Field; 1] ) // 3. Read current counter value fn get_counter(owner: AztecAddress) -> Field ``` -------------------------------- ### Execute Noir Circuit and Generate Proof Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/EXPLAINER.md Executes a compiled Noir circuit to generate a witness and proof, then converts the proof and verification key into field elements for on-chain consumption. ```typescript // 1. Load the compiled circuit const helloWorld = new Noir(circuitJson); // 2. Execute circuit with specific inputs const { witness } = await helloWorld.execute({ x: 1, // Private: only prover knows y: 2, // Public: everyone can see }); // 3. Generate the proof const backend = new UltraHonkBackend(circuitJson.bytecode); const proofData = await backend.generateProof(witness); // 4. Extract verification key const vk = await backend.getVerificationKey(); // 5. Convert to field elements for on-chain use const proofAsFields = deflattenFields(new RawBuffer(proofData.proof)); const vkAsFields = await barretenbergAPI.acirVkAsFieldsUltraHonk(vk); ``` -------------------------------- ### Create Custom UintNote with Deterministic Randomness Source: https://github.com/aztecprotocol/aztec-examples/blob/next/note-send-proof/readme.md Use this function to create a note with a provided randomness value, bypassing the default random() call for deterministic hash computation. Requires NoteType, NoteHash, and Packable traits for the Note type. ```noir pub fn create_note_with_randomness( context: &mut PrivateContext, owner: AztecAddress, storage_slot: Field, note: Note, randomness: Field, ) where Note: NoteType + NoteHash + Packable, { let note_hash = note.compute_note_hash(owner, storage_slot, randomness); notify_created_note(owner, storage_slot, randomness, ...); context.push_note_hash(note_hash); } ``` -------------------------------- ### Generate Proof Data Script Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/CLAUDE.md TypeScript script to execute the Noir circuit with specific inputs (x=1, y=2), generate an UltraHonk proof using Barretenberg, and serialize the proof, verification key, and public inputs to `data.json`. ```typescript import { Fr, Point } from '@aztec/foundation/fields'; import { AztecNodeClient, PXE } from '@aztec/aztec-node'; import { AztecAddress, Contract, ContractDeploymentInfo, Wallet } from '@aztec/aztec.js'; import { completePartial, encodeArguments, NoirFunction, NoirFunctionType, PXEConfig } from '@aztec/types'; import { generate_proof, verify_proof } from '@aztec/bb.js'; import * as fs from 'fs'; // Circuit inputs const x = 1; const y = 2; async function generate_data() { // Compile circuit to get ABI and bytecode const circuit = JSON.parse(fs.readFileSync('./circuit/target/hello_circuit.json', 'utf-8')); const noir_function: NoirFunction = { name: 'main', parameters: [ { name: 'x', type: { kind: 'field' } }, { name: 'y', type: { kind: 'field' } }, ], return_type: { kind: 'field' }, function_type: NoirFunctionType.SECRET, }; // Generate proof const { proof, public_inputs, vk } = await generate_proof(circuit, noir_function, [new Fr(x), new Fr(y)]); // Serialize and save data const data = { proof: Array.from(proof), public_inputs: Array.from(public_inputs.values()), vk: Array.from(vk), }; fs.writeFileSync('./scripts/data.json', JSON.stringify(data)); console.log('Proof data generated and saved to data.json'); } generate_data().catch((err) => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Integration Test with Vitest Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Demonstrates contract deployment and proof verification within a Vitest suite using an embedded wallet. ```typescript import { describe, expect, test, beforeAll } from "vitest" import { EmbeddedWallet } from "@aztec/wallets/embedded" import { createAztecNodeClient } from "@aztec/aztec.js/node" import { ValueNotEqualContract } from '../contract/artifacts/ValueNotEqual' import data from '../data.json' describe("Recursive Verification", () => { let wallet: EmbeddedWallet let ownerAddress: AztecAddress let contract: ValueNotEqualContract beforeAll(async () => { const aztecNode = await createAztecNodeClient('http://localhost:8080') wallet = await EmbeddedWallet.create(aztecNode, { ephemeral: true }) const accountManager = await wallet.createSchnorrAccount(Fr.random(), Fr.random()) await accountManager.getDeployMethod().send({ from: NO_FROM, fee: { paymentMethod } }) const accounts = await wallet.getAccounts() ownerAddress = accounts[0].item }, 600000) test("should deploy and verify proof", async () => { const { contract: deployed } = await ValueNotEqualContract.deploy( wallet, 10, ownerAddress, data.vkHash ).send({ from: ownerAddress, fee: { paymentMethod } }) contract = deployed expect(contract.address).toBeDefined() // Verify proof and increment const { receipt } = await contract.methods.increment( ownerAddress, data.vkAsFields, data.proofAsFields, data.publicInputs, ).send({ from: ownerAddress, fee: { paymentMethod } }) expect(receipt.executionResult).toBe(TxExecutionResult.SUCCESS) // Check counter const { result } = await contract.methods.get_counter(ownerAddress) .simulate({ from: ownerAddress }) expect(result).toBe(11n) }, 600000) }) ``` -------------------------------- ### Test Noir Circuit Source: https://github.com/aztecprotocol/aztec-examples/blob/next/recursive_verification/README.md Navigate to the circuit directory and run nargo tests to verify that the circuit correctly proves x ≠ y. ```bash cd circuit && nargo test ``` -------------------------------- ### Noir Circuit for Proof Generation (Not Equal) Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt A simple Noir circuit that proves two values are not equal. This circuit generates proofs that can be verified on-chain. ```noir fn main(x: Field, y: pub Field) { assert(x != y); } #[test] fn test_main() { main(1, 2); // Uncomment to make test fail // main(1, 1); } ``` -------------------------------- ### Vite Node.js Polyfills Configuration Source: https://github.com/aztecprotocol/aztec-examples/blob/next/test-wallet-webapp/README.md Configure `vite-plugin-node-polyfills` to provide browser-compatible implementations for Node.js APIs like `buffer`, `process`, and `path`, which are dependencies of the Aztec SDK. ```typescript nodePolyfillsFix({ include: ["buffer", "path", "process", "net", "tty"], }) ``` -------------------------------- ### Node.js Dependencies and Scripts Source: https://github.com/aztecprotocol/aztec-examples/blob/next/account-contract/README.md This file, package.json, manages Node.js dependencies and project scripts. ```json package.json ``` -------------------------------- ### Generate UltraHonk Proof Data Source: https://context7.com/aztecprotocol/aztec-examples/llms.txt Executes a Noir circuit, generates a proof, and exports the necessary artifacts for on-chain verification to a JSON file. ```typescript import { Noir } from '@aztec/noir-noir_js'; import circuitJson from '../circuit/target/hello_circuit.json' with { type: "json" } import { Barretenberg, UltraHonkBackend, deflattenFields } from '@aztec/bb.js'; import fs from 'fs' // Initialize Barretenberg API const barretenbergAPI = await Barretenberg.new({ threads: 1 }); const helloWorld = new Noir(circuitJson as any) // Execute circuit with inputs const { witness: mainWitness } = await helloWorld.execute({ x: 1, y: 2 }) // Initialize backend and generate proof const mainBackend = new UltraHonkBackend(circuitJson.bytecode, barretenbergAPI) const mainProofData = await mainBackend.generateProof(mainWitness, { verifierTarget: 'noir-recursive' }) // Verify proof locally const isValid = await mainBackend.verifyProof(mainProofData, { verifierTarget: 'noir-recursive' }) console.log(`Proof verification: ${isValid ? 'SUCCESS' : 'FAILED'}`) // Generate recursive proof artifacts const recursiveArtifacts = await mainBackend.generateRecursiveProofArtifacts( mainProofData.proof, mainProofData.publicInputs.length ) // Convert proof to fields if needed let proofAsFields = recursiveArtifacts.proofAsFields; if (proofAsFields.length === 0) { proofAsFields = deflattenFields(mainProofData.proof).map(f => f.toString()); } // Write artifacts for on-chain use const data = { vkAsFields: recursiveArtifacts.vkAsFields, vkHash: recursiveArtifacts.vkHash, proofAsFields: proofAsFields, publicInputs: mainProofData.publicInputs.map((p: string) => p.toString()), }; fs.writeFileSync('data.json', JSON.stringify(data, null, 2)) await barretenbergAPI.destroy() // Output: VK size: 115, Proof size: 508, Public inputs: 1 ```