[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DDRJS3935BME8X3MT0A4MZ":3,"skill-same:01M7DDRJS3935BME8X3MT0A4MZ":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7DDRJS3935BME8X3MT0A4MZ","noir",null,"Building privacy-preserving EVM apps with Noir — toolchain, pattern selection, commitment-nullifier flows, Solidity verifiers, tree state, and NoirJS. Use when building a Noir-based privacy app on EVM.","grmkris\u002Fsidequest","grmkris","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F15545195?v=4","01M7DDKZB6V5N6B5VT6XD5SHTF","Kris","01M7DDKZC95VVEHE13NBQ21EQ6",0,"MIT","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002F.agents\u002Fskills\u002Fethskills\u002Fnoir\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: noir\ndescription: Building privacy-preserving EVM apps with Noir — toolchain, pattern selection, commitment-nullifier flows, Solidity verifiers, tree state, and NoirJS. Use when building a Noir-based privacy app on EVM.\n---\n\n# Privacy Apps with Noir\n\n## What You Probably Got Wrong\n\n**\"Use `nargo prove` and `nargo verify`.\"** Those commands were removed. Nargo only compiles and executes. Proving and verification use `bb` (Barretenberg CLI) directly. If you generate `nargo prove` commands, they will fail.\n\n**\"I can use SHA256 for hashing in my circuit.\"** SHA256 costs ~30,000 gates in a circuit. Poseidon costs ~600. For in-circuit hashing, always use Poseidon. Poseidon was removed from the Noir standard library — you must add it as an external dependency. The correct import is `use poseidon::poseidon::bn254::hash_2` after adding the `noir-lang\u002Fposeidon` dependency to `Nargo.toml`. Not `std::hash::poseidon::bn254::hash_2` (removed from stdlib), not `Poseidon2::hash`, not `pedersen_hash`.\n\n**\"`pub` goes before the parameter name.\"** Noir 1.0 changed public input syntax: `pub merkle_root: Field` → `merkle_root: pub Field`. The old syntax gives \"Expected a pattern but found 'pub'\".\n\n**\"Set `compiler_version = \">=1.0.0-beta.3\"` in Nargo.toml.\"** `compiler_version` rejects beta strings — `>=1.0.0-beta.3` fails. Use `>=0.36.0` or omit `compiler_version` entirely.\n\n**\"I built a commitment-nullifier circuit so my app is private.\"** The ZK proof hides the link between commitment and nullifier, but `msg.sender` is public. If the same wallet deposits a commitment and later calls `act()` to withdraw\u002Fvote, anyone can link the two transactions onchain. The whole pattern is pointless unless the acting wallet is different from the committing wallet. Use a fresh burner wallet + a relayer or ERC-4337 paymaster to pay gas without revealing the link.\n\n**\"The generated HonkVerifier.sol works with any Solidity version.\"** The verifier generated by `bb write_solidity_verifier` requires `pragma solidity >=0.8.21` and EVM version `cancun`. If your Foundry project uses a lower version, add `solc_version = '0.8.27'` and `evm_version = 'cancun'` to `foundry.toml`.\n\n---\n\n## Quick Reference\n\nBeyond the corrections above:\n\n- **Solidity verifier = separate deploy** — deploy the generated `HonkVerifier.sol`, pass its address to your app contract constructor\n- **Input order must match everywhere** — circuit `pub` params, `proof.publicInputs`, and Solidity `verify()` call must be in the same order\n- **Poseidon ≠ Poseidon2** — different algorithms, different outputs. Don't mix them across circuit, offchain tree, and contract\n\n---\n\n## Toolchain (Current as of March 2026)\n\n### Install\n\nCheck if nargo and bb are already installed before running the installers:\n\n```bash\nnargo --version && bb --version\n```\n\nIf both commands return versions, you're set — skip the install. If either is missing:\n\n```bash\n# 1. Install nargo (Noir compiler) — always install nargo first\ncurl -L https:\u002F\u002Fraw.githubusercontent.com\u002Fnoir-lang\u002Fnoirup\u002Frefs\u002Fheads\u002Fmain\u002Finstall | bash\nnoirup\n\n# 2. Install bb (Barretenberg proving backend) — bbup reads your nargo version\n#    and installs the compatible bb automatically\ncurl -L https:\u002F\u002Fraw.githubusercontent.com\u002FAztecProtocol\u002Faztec-packages\u002Frefs\u002Fheads\u002Fmaster\u002Fbarretenberg\u002Fbbup\u002Finstall | bash\nbbup\n```\n\n**Order matters:** install nargo first, then run `bbup` — it auto-detects your nargo version and installs the compatible `bb`.\n\n### Project Structure\n\n```\nmy-circuit\u002F\n  Nargo.toml          # Project manifest (name, type, dependencies, external libs)\n  src\u002F\n    main.nr           # Circuit entry point\n  Prover.toml         # Witness inputs (private + public values)\n```\n\nCreate a new project:\n\n```bash\nnargo new my_circuit\ncd my_circuit\n```\n\n### Build Pipeline\n\nThe production build pipeline stops at circuit artifact, VK, and Solidity verifier. If asked for the minimal production build, say explicitly that `bb prove` \u002F `bb verify` below are optional local smoke tests only.\n\n```bash\n# 1. Compile circuit to ACIR\nnargo compile\n\n# 2. Execute with witness inputs (reads Prover.toml, writes target\u002F*.gz)\nnargo execute\n\n# 3. Generate verification key — --oracle_hash keccak is required for EVM compatibility\nbb write_vk --oracle_hash keccak -b target\u002Fmy_circuit.json -o target\u002F\n\n# 4. Generate Solidity verifier from the VK\nbb write_solidity_verifier -k target\u002Fvk -o target\u002FVerifier.sol\n```\n\n**Local-only proof smoke test** — useful before wiring up the frontend. All commands must use `--oracle_hash keccak` consistently, or you get serialization mismatches.\n\n```bash\nbb prove --oracle_hash keccak -b target\u002Fmy_circuit.json -w target\u002Fmy_circuit.gz -o target\u002F\nbb verify --oracle_hash keccak -p target\u002Fproof -k target\u002Fvk -i target\u002Fpublic_inputs\n```\n\nThe command is `bb write_solidity_verifier` — not `bb contract`, not `nargo codegen-verifier`.\n\n**Contract size warning:** Call this failure by name: the generated `HonkVerifier.sol` can exceed the 24KB EIP-170 contract size limit. For real deployments, enable the Solidity optimizer first:\n\n```toml\n# foundry.toml\n[profile.default]\noptimizer = true\noptimizer_runs = 200\n```\n\nIf you still hit the limit locally, run `anvil --code-size-limit 40960` and `forge script ... --code-size-limit 40960`. That flag is for local testing only — mainnet and major L2s still enforce the 24KB limit.\n\n### Build Artifacts and Hand-off\n\nTreat the generated files as interfaces between subsystems:\n\n- `target\u002Fmy_circuit.json` — circuit artifact consumed by NoirJS\n- `target\u002Fvk` — verification key used by `bb verify` and Solidity verifier generation\n- `target\u002FVerifier.sol` — generated verifier source; this is the source of truth for the verifier ABI. **This is a standalone contract that must be deployed separately.** Your app contract receives the verifier's deployed address in its constructor. Do not just import it — deploy it first, then pass the address.\n\nPick a stable layout and keep it consistent. A good default is:\n\n```text\ncircuits\u002Fmy_circuit\u002Ftarget\u002Fmy_circuit.json\ncontracts\u002Fsrc\u002Fverifiers\u002FHonkVerifier.sol\nfrontend\u002Fpublic\u002Fcircuits\u002Fmy_circuit.json\n```\n\nDo not hand-copy artifacts ad hoc in prompts or scripts. Models drift unless you make the hand-off explicit.\n\n---\n\n## Choosing the Right Pattern\n\nNot every privacy app needs a Merkle tree. Pick the simplest approach that fits:\n\n**Simple private proof** — prove a fact about private data without revealing it. No Merkle tree, no nullifier, no anonymity set. Just a circuit with private inputs, a public output, and a Solidity verifier. Examples: prove you're over 18 without revealing your age, prove your balance exceeds a threshold, prove a sealed bid is within range. The toolchain, Poseidon, NoirJS, and verifier sections above all apply — you just write a simpler circuit.\n\n**Commitment-nullifier pattern** — needed when multiple participants must act anonymously from a shared set. Participants commit secret hashes into a Merkle tree, then later prove membership and act from a different wallet. The Merkle tree is the anonymity set. The nullifier prevents double-action. Required for: anonymous voting, private withdrawals (Tornado Cash), anonymous airdrops, whistleblowing. This is harder to get right — see below.\n\nIf you're unsure: start with a simple private proof. Only reach for the commitment-nullifier pattern when you need unlinkability between a prior action (committing) and a later action (withdrawing\u002Fvoting).\n\n### Before writing any code, ask:\n\n1. **What needs to stay private?** A fact about data (age, balance, credential) → simple proof. *Which participant* performed an action → commitment-nullifier.\n2. **What happens after proof verification?** Withdraw funds, cast a vote, claim an airdrop, unlock access — this determines the contract's `act()` logic.\n3. **Can the same participant act more than once?** One vote per poll → nullifier scoped to `pollId`. One withdrawal per deposit → global nullifier. Unlimited access checks → no nullifier needed.\n4. **Does the caller's identity need to be hidden?** If yes, the user must act from a fresh wallet via a relayer or ERC-4337 paymaster. If no (e.g., private credential check), the same wallet is fine.\n5. **Which chain?** Check the compatibility table below. zkSync ERA works but has higher gas for BN254 precompiles.\n6. **What frontend?** Vite, Next.js \u002F Scaffold-ETH 2, or backend-only — each has different WASM configuration (see NoirJS section).\n\nGet these answers before choosing a pattern or writing a circuit. The answers determine tree depth, nullifier design, contract structure, and wallet flow.\n\n---\n\n## App Architecture (Commitment-Nullifier Apps)\n\nA working privacy app is not \"just a circuit.\" The model must wire five pieces together correctly:\n\n- **Circuit** — proves knowledge of a note (`nullifier`, `secret`) and membership in the commitment tree\n- **Onchain app contract** — accepts commitment inserts, tracks accepted roots, blocks reused nullifiers, and executes the action after proof verification\n- **Generated verifier** — created by `bb write_solidity_verifier`; its ABI is the source of truth\n- **Offchain tree mirror** — rebuilds the Merkle tree from insert events and produces `leafIndex`, siblings, and the root used for proving\n- **Frontend prover** — creates\u002Fsaves notes, loads the circuit artifact, executes Noir, generates the proof, serializes calldata, and submits the action transaction\n\nIf any one of these layers uses different hashes, input ordering, tree depth, or serialization, the app breaks even if the circuit compiles.\n\n---\n\n## The Commitment-Nullifier Pattern\n\nThe foundational primitive for privacy on Ethereum (Tornado Cash, Semaphore, MACI, Zupass).\n\n**How it works:** Many participants each commit a secret hash into a shared Merkle tree onchain. Later, any participant can prove \"I am one of the people who committed\" without revealing *which* one — by submitting a ZK proof from a different wallet. The Merkle tree is the anonymity set: the more people who commit, the larger the crowd you hide in, and the stronger the privacy. A nullifier hash prevents double-spending\u002Fdouble-voting without revealing identity.\n\nThis is why scale matters — a commitment tree with 3 entries gives weak privacy (1-in-3), while a tree with 10,000 entries makes identifying the actor practically impossible.\n\n### Nargo.toml\n\nPoseidon is no longer in the Noir standard library — add it as an external dependency:\n\n```toml\n[package]\nname = \"my_circuit\"\ntype = \"bin\"\n\n[dependencies]\nposeidon = { git = \"https:\u002F\u002Fgithub.com\u002Fnoir-lang\u002Fposeidon\", tag = \"v0.2.6\" }\n```\n\n### Note Lifecycle (What the User Must Save)\n\nAt commitment time, generate two random private fields:\n\n- `nullifier`\n- `secret`\n\nThen compute the commitment and persist a note locally. If the note is lost, the user cannot later prove membership or spend\u002Fvote.\n\n```typescript\ntype PrivacyNote = {\n  nullifier: string;\n  secret: string;\n  commitment: string;\n  chainId: number;\n  contract: `0x${string}`;\n  treeDepth: number;\n  leafIndex?: number;\n};\n```\n\nDefault flow:\n\n1. Generate `nullifier` and `secret`.\n2. Compute `commitment`.\n3. Submit the commitment insertion transaction.\n4. Read the insert event and persist `leafIndex` plus the new root.\n5. Later, rebuild the tree from events, derive siblings for `leafIndex`, and prove against an accepted root.\n\nThe app must make this lifecycle explicit. A model that only writes the circuit usually forgets note persistence, `leafIndex`, or event replay.\n\n### Circuit Implementation\n\n```noir\n\u002F\u002F src\u002Fmain.nr\nuse poseidon::poseidon::bn254::hash_1;\nuse poseidon::poseidon::bn254::hash_2;\n\nfn main(\n    \u002F\u002F Private inputs (known only to prover)\n    nullifier: Field,\n    secret: Field,\n    merkle_path: [Field; 20],      \u002F\u002F Sibling hashes (tree depth 20)\n    merkle_indices: [u1; 20],       \u002F\u002F 0 = left child, 1 = right child (u1 enforces binary)\n\n    \u002F\u002F Public inputs (visible to verifier\u002Fcontract)\n    merkle_root: pub Field,\n    nullifier_hash: pub Field,\n) {\n    \u002F\u002F 1. Recompute the commitment from private inputs\n    let commitment = hash_2([nullifier, secret]);\n\n    \u002F\u002F 2. Verify the commitment exists in the Merkle tree\n    let computed_root = compute_merkle_root(commitment, merkle_path, merkle_indices);\n    assert(computed_root == merkle_root, \"Merkle proof invalid\");\n\n    \u002F\u002F 3. Verify the nullifier hash matches\n    let computed_nullifier_hash = hash_1([nullifier]);\n    assert(computed_nullifier_hash == nullifier_hash, \"Nullifier hash mismatch\");\n}\n\nfn compute_merkle_root(\n    leaf: Field,\n    path: [Field; 20],\n    indices: [u1; 20],\n) -> Field {\n    let mut current = leaf;\n    for i in 0..20 {\n        \u002F\u002F u1 type enforces binary at compile time, no manual assert needed\n        let (left, right) = if indices[i] == 0 {\n            (current, path[i])\n        } else {\n            (path[i], current)\n        };\n        current = hash_2([left, right]);\n    }\n    current\n}\n```\n\n### Production Hardening: Domain Separation and Action Binding\n\nThe circuit above is the minimal pattern. Production apps should domain-separate hashes and bind the proof to a specific action. Commitments and nullifiers must use different domains.\n\nFor action-scoped apps such as voting, bind nullifier usage to an `external_nullifier` (for example `pollId`):\n\n```noir\nuse poseidon::poseidon::bn254::hash_2;\n\nfn main(\n    nullifier: Field,\n    secret: Field,\n    merkle_path: [Field; 20],\n    merkle_indices: [u1; 20],\n    merkle_root: pub Field,\n    external_nullifier: pub Field,\n    nullifier_hash: pub Field,\n) {\n    let note_secret = hash_2([nullifier, secret]);\n    let commitment = hash_2([1, note_secret]); \u002F\u002F 1 = commitment domain\n\n    let computed_root = compute_merkle_root(commitment, merkle_path, merkle_indices);\n    assert(computed_root == merkle_root, \"Merkle proof invalid\");\n\n    \u002F\u002F 2 = nullifier domain; external_nullifier scopes usage to a poll\u002Faction\n    let nullifier_domain = hash_2([2, external_nullifier]);\n    let computed_nullifier_hash = hash_2([nullifier_domain, nullifier]);\n    assert(computed_nullifier_hash == nullifier_hash, \"Nullifier hash mismatch\");\n}\n```\n\n### Solidity Contract Integration\n\nThe generated verifier contract is the source of truth. If you wrap it behind an interface like the one below, inspect the generated verifier ABI first and mirror it exactly, or add a dedicated adapter contract with a stable app-facing interface.\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\ninterface IVerifier {\n    function verify(bytes calldata proof, bytes32[] calldata publicInputs)\n        external view returns (bool);\n}\n\ncontract PrivacyPool {\n    IVerifier public immutable verifier;\n    bytes32 public merkleRoot;\n    mapping(bytes32 => bool) public usedNullifiers;\n\n    constructor(address _verifier) {\n        verifier = IVerifier(_verifier);\n    }\n\n    \u002F\u002F msg.sender is public — see \"same wallet\" warning above.\n    \u002F\u002F Only mutate state after verify() succeeds.\n    function act(bytes calldata _proof, bytes32 _merkleRoot, bytes32 _nullifierHash) external {\n        require(!usedNullifiers[_nullifierHash], \"Already acted\");\n        require(_merkleRoot == merkleRoot, \"Invalid root\");\n\n        \u002F\u002F Public inputs order MUST match the circuit's pub parameter order\n        bytes32[] memory publicInputs = new bytes32[](2);\n        publicInputs[0] = _merkleRoot;       \u002F\u002F pub merkle_root\n        publicInputs[1] = _nullifierHash;    \u002F\u002F pub nullifier_hash\n        require(verifier.verify(_proof, publicInputs), \"Invalid proof\");\n\n        \u002F\u002F Only mutate state after proof verification succeeds\n        usedNullifiers[_nullifierHash] = true;\n    }\n}\n```\n\n### Contract State Model\n\nFor a real app, the contract needs more than `merkleRoot` + `usedNullifiers`:\n\n- Emit an insert event with the commitment, leaf index, and resulting root\n- Store used nullifiers\n- Make the root-acceptance policy explicit: recent `knownRoots` or `currentRoot`-only\n- Verify proofs before success events, transfers\u002Fvotes, or nullifier writes\n\nGood default:\n\n```solidity\nevent CommitmentInserted(bytes32 indexed commitment, uint256 indexed leafIndex, bytes32 root);\n\nmapping(bytes32 => bool) public usedNullifiers;\nmapping(bytes32 => bool) public knownRoots; \u002F\u002F keep recent roots by default\nbytes32 public currentRoot;\n```\n\n**Root policy:** default to recent `knownRoots`. If you intentionally accept only `currentRoot`, say so explicitly and require clients to prove against the latest root.\n\nClients derive siblings by replaying `CommitmentInserted` into the offchain tree mirror; the contract never returns witness paths.\n\n### Onchain Commitment Storage (LeanIMT)\n\nMost Noir ZK apps store commitments in an onchain Merkle tree. If asked how commitments are stored onchain, name all three pieces: onchain `@zk-kit\u002Flean-imt.sol` + deployed `PoseidonT3`; offchain `@zk-kit\u002Flean-imt`; witness path from `tree.generateProof(leafIndex)`.\n\n**Solidity:**\n\n```bash\nnpm install @zk-kit\u002Flean-imt.sol\n```\n\n```solidity\nimport {LeanIMT, LeanIMTData} from \"@zk-kit\u002Flean-imt.sol\u002FLeanIMT.sol\";\n```\n\nDeploy `PoseidonT3` alongside; the tree contract uses it internally for hashing. The contract maintains the Merkle root automatically — users call `insert(commitment)`.\n\n**JavaScript (client-side tree mirror):**\n\n```bash\nnpm install @zk-kit\u002Flean-imt\n```\n```typescript\nimport { LeanIMT } from \"@zk-kit\u002Flean-imt\";\nconst { siblings, pathIndices } = tree.generateProof(leafIndex); \u002F\u002F after replaying CommitmentInserted events\n```\n---\n\n## Merkle Proof with zk-kit\n\nFor production Merkle trees, use the `@zk-kit.noir` library:\n\n```toml\n# Nargo.toml\n[dependencies]\nbinary_merkle_root = { tag = \"main\", git = \"https:\u002F\u002Fgithub.com\u002Fprivacy-scaling-explorations\u002Fzk-kit.noir\", directory = \"packages\u002Fbinary-merkle-root\" }\n```\n\n```noir\nuse binary_merkle_root::binary_merkle_root;\nuse poseidon::poseidon::bn254::hash_2;\n\nglobal TREE_DEPTH: u32 = 20;\n\nfn main(\n    leaf: Field,\n    indices: [u1; TREE_DEPTH],       \u002F\u002F u1 enforces binary, no manual assert needed\n    siblings: [Field; TREE_DEPTH],\n    root: pub Field,\n) {\n    let computed = binary_merkle_root(hash_2, leaf, TREE_DEPTH, indices, siblings);\n    assert(computed == root, \"Invalid Merkle proof\");\n}\n```\n\nThe function takes 5 args: `hasher`, `leaf`, `depth`, `indices`, `siblings`. The `indices` type is `[u1; MAX_DEPTH]` — the `u1` type constrains values to 0 or 1 at the type level, so you don't need manual binary assertions like `assert(indices[i] * (indices[i] - 1) == 0)`.\n\n---\n\n## Frontend Proof Generation (NoirJS)\n\nThe packages are `@noir-lang\u002Fnoir_js` + `@aztec\u002Fbb.js`. NOT `@noir-lang\u002Fbackend_barretenberg` (old, deprecated). The class is `UltraHonkBackend`, NOT `UltraPlonkBackend` (old).\n\n### Package Setup\n\n```bash\nnpm install @noir-lang\u002Fnoir_js \"@aztec\u002Fbb.js@$(bb --version)\"\n# ⚠ The @aztec\u002Fbb.js version must exactly match your bb CLI version (check with `bb --version`). A mismatch produces different proof serialization, causing onchain verification to fail.\n```\n\n### Vite Configuration\n\nNoirJS uses WASM and requires top-level await:\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig } from \"vite\";\nimport { nodePolyfills } from \"vite-plugin-node-polyfills\";\n\nexport default defineConfig({\n  plugins: [nodePolyfills()],\n  optimizeDeps: {\n    esbuildOptions: { target: \"esnext\" },\n  },\n  build: {\n    target: \"esnext\",\n  },\n});\n```\n\n### Next.js \u002F Scaffold-ETH 2 Configuration\n\n```typescript\n\u002F\u002F next.config.js\nconst nextConfig = {\n  webpack: (config) => {\n    config.experiments = { ...config.experiments, asyncWebAssembly: true };\n    return config;\n  },\n};\nmodule.exports = nextConfig;\n```\n\n```typescript\n\u002F\u002F components\u002FProofGenerator.tsx\n\"use client\";\nimport dynamic from \"next\u002Fdynamic\";\n\n\u002F\u002F All Noir components must be client-only — WASM doesn't run in SSR\nconst NoirProver = dynamic(() => import(\".\u002FNoirProver\"), { ssr: false });\n```\n\nCircuit artifact (`my_circuit.json`) must be copied to `public\u002F` and loaded via `fetch()` — cross-package JSON imports don't work in Next.js:\n\n```typescript\nconst circuit = await fetch(\"\u002Fmy_circuit.json\").then(r => r.json());\n```\n\n### Generating Proofs in the Browser\n\n```typescript\nimport { Noir } from \"@noir-lang\u002Fnoir_js\";\nimport { Barretenberg, UltraHonkBackend } from \"@aztec\u002Fbb.js\";\nimport circuit from \"..\u002Fcircuit\u002Ftarget\u002Fmy_circuit.json\";\n\n\u002F\u002F 1. Initialize Barretenberg instance, then backend and Noir\nconst bb = await Barretenberg.new();\nconst backend = new UltraHonkBackend(circuit.bytecode, bb);\nconst noir = new Noir(circuit);\n\n\u002F\u002F 2. Execute circuit (generates witness)\nconst inputs = {\n  nullifier: \"0x1234...\",\n  secret: \"0xabcd...\",\n  merkle_path: [\"0x...\", \"0x...\", ...],\n  merkle_indices: [0, 1, 0, ...],\n  merkle_root: \"0x...\",\n  nullifier_hash: \"0x...\",\n};\nconst { witness } = await noir.execute(inputs);\n\n\u002F\u002F 3. Generate proof — { keccak: true } matches --oracle_hash keccak used for the verifier\nconst proof = await backend.generateProof(witness, { keccak: true });\n\u002F\u002F proof.proof is Uint8Array — the raw proof bytes\n\u002F\u002F proof.publicInputs is string[] — the public inputs\n\nconst bytesToHex = (bytes: Uint8Array) =>\n  `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n\nconst toBytes32 = (field: string) =>\n  `0x${field.replace(\u002F^0x\u002F, \"\").padStart(64, \"0\")}` as `0x${string}`;\n\nconst proofHex = bytesToHex(proof.proof);\nconst publicInputs = proof.publicInputs.map(toBytes32);\n\n\u002F\u002F 4. Send to contract\nconst tx = await contract.act(\n  proofHex,                                 \u002F\u002F bytes calldata\n  publicInputs[0],                          \u002F\u002F merkle_root\n  publicInputs[1],                          \u002F\u002F nullifier_hash\n);\n```\n\n- `proof.proof` is `Uint8Array` — serialize it to `0x...` before sending over RPC\n- `proof.publicInputs` are strings — normalize them to 32-byte hex before comparing or passing to Solidity\n- EVM compatibility requires `--oracle_hash keccak` on CLI commands (see Build Pipeline above) AND `{ keccak: true }` in `generateProof()` — both must be set or you get serialization mismatches\n- Proof generation takes 5-30 seconds in browser depending on circuit size\n- Cleanup: call `bb.destroy()` when done\n- The generated verifier ABI is the source of truth; if your app uses an adapter, make the adapter match that ABI, not a guessed interface\n- **No `Buffer` in browser** — convert `Uint8Array` to hex directly\n\n### Serialization Boundary\n\nMost zk app failures happen here:\n\n- Circuit `pub` parameter order\n- NoirJS `proof.publicInputs` order\n- Solidity verifier input order\n- App contract wrapper\u002Fadaptor order\n\nThese four must match exactly.\n\nHard rule: inspect the generated verifier ABI and mirror it exactly. Do not assume every verifier exposes a generic `verify(bytes, bytes32[])` signature just because one example does.\n\n### Hash Parity Across Circuit, Tree, and Contract\n\nIf your circuit uses `poseidon::poseidon::bn254::hash_2`, then every other layer must use the same algorithm and input ordering:\n\n- commitment creation\n- Merkle parent hashing\n- offchain tree mirror\n- onchain tree contract\n\nDo not mix Poseidon, Poseidon2, and Keccak. `poseidon2Hash` is not a substitute for `poseidon::poseidon::bn254::hash_2`.\n\nBefore building the full app, test one leaf hash and one parent hash with known inputs across every layer and assert that the outputs match exactly.\n\n---\n\n## Chain Compatibility\n\nNoir\u002FBarretenberg proofs verify on any EVM chain with BN254 precompiles (ecAdd, ecMul, ecPairing at addresses 0x06-0x08).\n\n| Chain | Compatible | Notes |\n|-------|-----------|-------|\n| Ethereum mainnet | Yes | |\n| Optimism | Yes | |\n| Arbitrum | Yes | |\n| Base | Yes | |\n| Scroll | Yes | |\n| Polygon PoS | Yes | |\n| zkSync ERA | Yes | BN254 precompiles at standard addresses; implemented as smart contracts (higher gas) |\n| Polygon zkEVM | **No** | Being shut down — do not build on it |\n\n---\n\n## Circuit Security Checklist\n\n- [ ] All private inputs are constrained (no unconstrained witness values that could be manipulated)\n- [ ] Public inputs minimized — only what the verifier contract needs\n- [ ] Domain separation in hashes — different prefixes for commitments vs nullifiers (prevents cross-protocol replay)\n- [ ] Action-scoped apps bind nullifier usage to an `external_nullifier` \u002F `pollId` \u002F recipient \u002F action id\n- [ ] Nullifier prevents double-action (contract checks and stores used nullifier hashes)\n- [ ] Small-domain values not directly hashed as public outputs (if vote is 0 or 1, `hash(0)` and `hash(1)` are trivially brutable — add a salt)\n- [ ] Merkle tree depth matches between circuit (fixed at compile time) and contract\n- [ ] Merkle indices use `u1` type (enforces binary at compile time) — if using `Field`, manually constrain to 0\u002F1\n- [ ] Poseidon hash compatibility verified between Noir circuit, offchain tree mirror, and any onchain Poseidon library\n- [ ] The app persists notes (`nullifier`, `secret`, `commitment`, chain\u002Fcontract metadata, `leafIndex`)\n- [ ] The contract emits insert events with `leafIndex` and root so the client can rebuild the tree\n- [ ] The accepted-root policy is explicit (recent root history vs current-root-only)\n- [ ] The generated verifier ABI was inspected and mirrored exactly\n- [ ] Never deploy `MockVerifier`, even locally — deploy scripts and dev\u002Ftestnet wiring use the real `HonkVerifier`; `MockVerifier` is only for narrow unit tests\n\n---\n\n## Testing the App Core\n\nDo not stop at \"the circuit compiles.\" A working zk app needs tests at every boundary:\n\n1. **Circuit witness test** — fixed inputs should produce the expected public inputs and root checks.\n2. **Hash parity test** — the same leaf and parent inputs must hash identically in the circuit, offchain tree mirror, and onchain tree library.\n3. **Real-verifier integration test** — deploy the generated verifier and verify one real proof against it.\n4. **End-to-end app test** — insert a commitment, rebuild the tree from events, generate a browser\u002Fbackend proof, submit `act()`, and assert success.\n5. **Failure-path tests** — reused nullifier, wrong root, wrong sibling ordering, stale root, and mismatched public input order must all fail.\n\n`MockVerifier` is only for narrow unit tests. Deploy scripts, local dev wiring, and integration tests use the real generated `HonkVerifier`.\n\n---\n\n## AI Agent Tooling\n\nThis skill corrects common mistakes. For live, searchable access to Noir documentation, stdlib, and example circuits, agents can use the [noir-mcp-server](https:\u002F\u002Fgithub.com\u002Fcritesjosh\u002Fnoir-mcp-server):\n\n```bash\nclaude mcp add noir-mcp -- npx @critesjosh\u002Fnoir-mcp-server@latest\n```\n\nAfter adding the server, run `\u002Freload-plugins` so the new tools become available in the current session.\n\nIndexes the Noir compiler repo, standard library, examples, and community libraries (bignum, zk-kit.noir, etc.). Useful for looking up function signatures and browsing code beyond what this skill covers. If the npm package is unavailable, clone the repo and run directly.\n\nFor idiomatic, gate-efficient Noir style (hint-and-verify with `unconstrained`, ACIR vs Brillig tradeoffs, leveraging the type system, `assert_eq`, comparison costs), see the official noir-lang skill: [noir-idioms\u002FSKILL.md](https:\u002F\u002Fraw.githubusercontent.com\u002Fnoir-lang\u002Fnoir\u002Fmaster\u002F.claude\u002Fskills\u002Fnoir-idioms\u002FSKILL.md). This skill covers privacy-app architecture; that one covers writing efficient circuits.\n\n---\n\n## Example Repos and Building Blocks\n\nUse app-pattern repos for end-to-end architecture. Use primitives for narrow cryptographic building blocks.\n\n### App Patterns\n\n- **Simple private proof** — [noir-lang\u002Ftiny-noirjs-app](https:\u002F\u002Fgithub.com\u002Fnoir-lang\u002Ftiny-noirjs-app). Minimal NoirJS app for proving a private fact without a Merkle tree, nullifier, or signed-document flow. Good reference for age-threshold or balance-threshold style proofs.\n- **Anonymous voting** — [scaffold-eth\u002Fse-2-challenges (zk-voting branch)](https:\u002F\u002Fgithub.com\u002Fscaffold-eth\u002Fse-2-challenges\u002Ftree\u002Fchallenge-zk-voting). Full Scaffold-ETH 2 + Noir app: commitment-nullifier flow, LeanIMT membership proofs, Solidity verifier wiring, proof generation, and burner-wallet UX. [Challenge guide](https:\u002F\u002Fspeedrunethereum.com\u002Fchallenge\u002Fzk-voting).\n- **Private withdrawals \u002F mixer** — [Cyfrin\u002Fzk-mixer-cu](https:\u002F\u002Fgithub.com\u002FCyfrin\u002Fzk-mixer-cu). Direct Tornado-style Noir reference: deposit commitments into a Merkle tree, then withdraw with a membership proof and nullifier. Good for commitment-nullifier private withdrawal flows. Educational repo, not a production deployment reference.\n- **Private identity** — [zkpassport\u002Fcircuits](https:\u002F\u002Fgithub.com\u002Fzkpassport\u002Fcircuits). Selective-disclosure identity circuits: prove attributes like age or nationality without revealing the full credential.\n- **ZK email** — [zkemail\u002Fzkemail.nr](https:\u002F\u002Fgithub.com\u002Fzkemail\u002Fzkemail.nr). Email-auth proof system: DKIM verification plus selective disclosure of sender, subject, or body fragments without revealing the whole message.\n\n### Primitives\n\n- **Signature verification** — [colinnielsen\u002Fecrecover-noir](https:\u002F\u002Fgithub.com\u002Fcolinnielsen\u002Fecrecover-noir). Focused secp256k1 \u002F Ethereum signature recovery primitive for credentials, attestations, and account-linked proofs. Useful as a building block, not a full app architecture. Inspect the math and interface shape, but do not copy exact Noir syntax or package versions blindly.\n","# Privacy Apps with Noir\n\n## What You Probably Got Wrong\n\n**\"Use `nargo prove` and `nargo verify`.\"** Those commands were removed. Nargo only compiles and executes. Proving and verification use `bb` (Barretenberg CLI) directly. If you generate `nargo prove` commands, they will fail.\n\n**\"I can use SHA256 for hashing in my circuit.\"** SHA256 costs ~30,000 gates in a circuit. Poseidon costs ~600. For in-circuit hashing, always use Poseidon. Poseidon was removed from the Noir standard library — you must add it as an external dependency. The correct import is `use poseidon::poseidon::bn254::hash_2` after adding the `noir-lang\u002Fposeidon` dependency to `Nargo.toml`. Not `std::hash::poseidon::bn254::hash_2` (removed from stdlib), not `Poseidon2::hash`, not `pedersen_hash`.\n\n**\"`pub` goes before the parameter name.\"** Noir 1.0 changed public input syntax: `pub merkle_root: Field` → `merkle_root: pub Field`. The old syntax gives \"Expected a pattern but found 'pub'\".\n\n**\"Set `compiler_version = \">=1.0.0-beta.3\"` in Nargo.toml.\"** `compiler_version` rejects beta strings — `>=1.0.0-beta.3` fails. Use `>=0.36.0` or omit `compiler_version` entirely.\n\n**\"I built a commitment-nullifier circuit so my app is private.\"** The ZK proof hides the link between commitment and nullifier, but `msg.sender` is public. If the same wallet deposits a commitment and later calls `act()` to withdraw\u002Fvote, anyone can link the two transactions onchain. The whole pattern is pointless unless the acting wallet is different from the committing wallet. Use a fresh burner wallet + a relayer or ERC-4337 paymaster to pay gas without revealing the link.\n\n**\"The generated HonkVerifier.sol works with any Solidity version.\"** The verifier generated by `bb write_solidity_verifier` requires `pragma solidity >=0.8.21` and EVM version `cancun`. If your Foundry project uses a lower version, add `solc_version = '0.8.27'` and `evm_version = 'cancun'` to `foundry.toml`.\n\n---\n\n## Quick Reference\n\nBeyond the corrections above:\n\n- **Solidity verifier = separate deploy** — deploy the generated `HonkVerifier.sol`, pass its address to your app contract constructor\n- **Input order must match everywhere** — circuit `pub` params, `proof.publicInputs`, and Solidity `verify()` call must be in the same order\n- **Poseidon ≠ Poseidon2** — different algorithms, different outputs. Don't mix them across circuit, offchain tree, and contract\n\n---\n\n## Toolchain (Current as of March 2026)\n\n### Install\n\nCheck if nargo and bb are already installed before running the installers:\n\n```bash\nnargo --version && bb --version\n```\n\nIf both commands return versions, you're set — skip the install. If either is missing:\n\n```bash\n# 1. Install nargo (Noir compiler) — always install nargo first\ncurl -L https:\u002F\u002Fraw.githubusercontent.com\u002Fnoir-lang\u002Fnoirup\u002Frefs\u002Fheads\u002Fmain\u002Finstall | bash\nnoirup\n\n# 2. Install bb (Barretenberg proving backend) — bbup reads your nargo version\n#    and installs the compatible bb automatically\ncurl -L https:\u002F\u002Fraw.githubusercontent.com\u002FAztecProtocol\u002Faztec-packages\u002Frefs\u002Fheads\u002Fmaster\u002Fbarretenberg\u002Fbbup\u002Finstall | bash\nbbup\n```\n\n**Order matters:** install nargo first, then run `bbup` — it auto-detects your nargo version and installs the compatible `bb`.\n\n### Project Structure\n\n```\nmy-circuit\u002F\n  Nargo.toml          # Project manifest (name, type, dependencies, external libs)\n  src\u002F\n    main.nr           # Circuit entry point\n  Prover.toml         # Witness inputs (private + public values)\n```\n\nCreate a new project:\n\n```bash\nnargo new my_circuit\ncd my_circuit\n```\n\n### Build Pipeline\n\nThe production build pipeline stops at circuit artifact, VK, and Solidity verifier. If asked for the minimal production build, say explicitly that `bb prove` \u002F `bb verify` below are optional local smoke tests only.\n\n```bash\n# 1. Compile circuit to ACIR\nnargo compile\n\n# 2. Execute with witness inputs (reads Prover.toml, writes target\u002F*.gz)\nnargo execute\n\n# 3. Generate verification key — --oracle_hash keccak is required for EVM compatibility\nbb write_vk --oracle_hash keccak -b target\u002Fmy_circuit.json -o target\u002F\n\n# 4. Generate Solidity verifier from the VK\nbb write_solidity_verifier -k target\u002Fvk -o target\u002FVerifier.sol\n```\n\n**Local-only proof smoke test** — useful before wiring up the frontend. All commands must use `--oracle_hash keccak` consistently, or you get serialization mismatches.\n\n```bash\nbb prove --oracle_hash keccak -b target\u002Fmy_circuit.json -w target\u002Fmy_circuit.gz -o target\u002F\nbb verify --oracle_hash keccak -p target\u002Fproof -k target\u002Fvk -i target\u002Fpublic_inputs\n```\n\nThe command is `bb write_solidity_verifier` — not `bb contract`, not `nargo codegen-verifier`.\n\n**Contract size warning:** Call this failure by name: the generated `HonkVerifier.sol` can exceed the 24KB EIP-170 contract size limit. For real deployments, enable the Solidity optimizer first:\n\n```toml\n# foundry.toml\n[profile.default]\noptimizer = true\noptimizer_runs = 200\n```\n\nIf you still hit the limit locally, run `anvil --code-size-limit 40960` and `forge script ... --code-size-limit 40960`. That flag is for local testing only — mainnet and major L2s still enforce the 24KB limit.\n\n### Build Artifacts and Hand-off\n\nTreat the generated files as interfaces between subsystems:\n\n- `target\u002Fmy_circuit.json` — circuit artifact consumed by NoirJS\n- `target\u002Fvk` — verification key used by `bb verify` and Solidity verifier generation\n- `target\u002FVerifier.sol` — generated verifier source; this is the source of truth for the verifier ABI. **This is a standalone contract that must be deployed separately.** Your app contract receives the verifier's deployed address in its constructor. Do not just import it — deploy it first, then pass the address.\n\nPick a stable layout and keep it consistent. A good default is:\n\n```text\ncircuits\u002Fmy_circuit\u002Ftarget\u002Fmy_circuit.json\ncontracts\u002Fsrc\u002Fverifiers\u002FHonkVerifier.sol\nfrontend\u002Fpublic\u002Fcircuits\u002Fmy_circuit.json\n```\n\nDo not hand-copy artifacts ad hoc in prompts or scripts. Models drift unless you make the hand-off explicit.\n\n---\n\n## Choosing the Right Pattern\n\nNot every privacy app needs a Merkle tree. Pick the simplest approach that fits:\n\n**Simple private proof** — prove a fact about private data without revealing it. No Merkle tree, no nullifier, no anonymity set. Just a circuit with private inputs, a public output, and a Solidity verifier. Examples: prove you're over 18 without revealing your age, prove your balance exceeds a threshold, prove a sealed bid is within range. The toolchain, Poseidon, NoirJS, and verifier sections above all apply — you just write a simpler circuit.\n\n**Commitment-nullifier pattern** — needed when multiple participants must act anonymously from a shared set. Participants commit secret hashes into a Merkle tree, then later prove membership and act from a different wallet. The Merkle tree is the anonymity set. The nullifier prevents double-action. Required for: anonymous voting, private withdrawals (Tornado Cash), anonymous airdrops, whistleblowing. This is harder to get right — see below.\n\nIf you're unsure: start with a simple private proof. Only reach for the commitment-nullifier pattern when you need unlinkability between a prior action (committing) and a later action (withdrawing\u002Fvoting).\n\n### Before writing any code, ask:\n\n1. **What needs to stay private?** A fact about data (age, balance, credential) → simple proof. *Which participant* performed an action → commitment-nullifier.\n2. **What happens after proof verification?** Withdraw funds, cast a vote, claim an airdrop, unlock access — this determines the contract's `act()` logic.\n3. **Can the same participant act more than once?** One vote per poll → nullifier scoped to `pollId`. One withdrawal per deposit → global nullifier. Unlimited access checks → no nullifier needed.\n4. **Does the caller's identity need to be hidden?** If yes, the user must act from a fresh wallet via a relayer or ERC-4337 paymaster. If no (e.g., private credential check), the same wallet is fine.\n5. **Which chain?** Check the compatibility table below. zkSync ERA works but has higher gas for BN254 precompiles.\n6. **What frontend?** Vite, Next.js \u002F Scaffold-ETH 2, or backend-only — each has different WASM configuration (see NoirJS section).\n\nGet these answers before choosing a pattern or writing a circuit. The answers determine tree depth, nullifier design, contract structure, and wallet flow.\n\n---\n\n## App Architecture (Commitment-Nullifier Apps)\n\nA working privacy app is not \"just a circuit.\" The model must wire five pieces together correctly:\n\n- **Circuit** — proves knowledge of a note (`nullifier`, `secret`) and membership in the commitment tree\n- **Onchain app contract** — accepts commitment inserts, tracks accepted roots, blocks reused nullifiers, and executes the action after proof verification\n- **Generated verifier** — created by `bb write_solidity_verifier`; its ABI is the source of truth\n- **Offchain tree mirror** — rebuilds the Merkle tree from insert events and produces `leafIndex`, siblings, and the root used for proving\n- **Frontend prover** — creates\u002Fsaves notes, loads the circuit artifact, executes Noir, generates the proof, serializes calldata, and submits the action transaction\n\nIf any one of these layers uses different hashes, input ordering, tree depth, or serialization, the app breaks even if the circuit compiles.\n\n---\n\n## The Commitment-Nullifier Pattern\n\nThe foundational primitive for privacy on Ethereum (Tornado Cash, Semaphore, MACI, Zupass).\n\n**How it works:** Many participants each commit a secret hash into a shared Merkle tree onchain. Later, any participant can prove \"I am one of the people who committed\" without revealing *which* one — by submitting a ZK proof from a different wallet. The Merkle tree is the anonymity set: the more people who commit, the larger the crowd you hide in, and the stronger the privacy. A nullifier hash prevents double-spending\u002Fdouble-voting without revealing identity.\n\nThis is why scale matters — a commitment tree with 3 entries gives weak privacy (1-in-3), while a tree with 10,000 entries makes identifying the actor practically impossible.\n\n### Nargo.toml\n\nPoseidon is no longer in the Noir standard library — add it as an external dependency:\n\n```toml\n[package]\nname = \"my_circuit\"\ntype = \"bin\"\n\n[dependencies]\nposeidon = { git = \"https:\u002F\u002Fgithub.com\u002Fnoir-lang\u002Fposeidon\", tag = \"v0.2.6\" }\n```\n\n### Note Lifecycle (What the User Must Save)\n\nAt commitment time, generate two random private fields:\n\n- `nullifier`\n- `secret`\n\nThen compute the commitment and persist a note locally. If the note is lost, the user cannot later prove membership or spend\u002Fvote.\n\n```typescript\ntype PrivacyNote = {\n  nullifier: string;\n  secret: string;\n  commitment: string;\n  chainId: number;\n  contract: `0x${string}`;\n  treeDepth: number;\n  leafIndex?: number;\n};\n```\n\nDefault flow:\n\n1. Generate `nullifier` and `secret`.\n2. Compute `commitment`.\n3. Submit the commitment insertion transaction.\n4. Read the insert event and persist `leafIndex` plus the new root.\n5. Later, rebuild the tree from events, derive siblings for `leafIndex`, and prove against an accepted root.\n\nThe app must make this lifecycle explicit. A model that only writes the circuit usually forgets note persistence, `leafIndex`, or event replay.\n\n### Circuit Implementation\n\n```noir\n\u002F\u002F src\u002Fmain.nr\nuse poseidon::poseidon::bn254::hash_1;\nuse poseidon::poseidon::bn254::hash_2;\n\nfn main(\n    \u002F\u002F Private inputs (known only to prover)\n    nullifier: Field,\n    secret: Field,\n    merkle_path: [Field; 20],      \u002F\u002F Sibling hashes (tree depth 20)\n    merkle_indices: [u1; 20],       \u002F\u002F 0 = left child, 1 = right child (u1 enforces binary)\n\n    \u002F\u002F Public inputs (visible to verifier\u002Fcontract)\n    merkle_root: pub Field,\n    nullifier_hash: pub Field,\n) {\n    \u002F\u002F 1. Recompute the commitment from private inputs\n    let commitment = hash_2([nullifier, secret]);\n\n    \u002F\u002F 2. Verify the commitment exists in the Merkle tree\n    let computed_root = compute_merkle_root(commitment, merkle_path, merkle_indices);\n    assert(computed_root == merkle_root, \"Merkle proof invalid\");\n\n    \u002F\u002F 3. Verify the nullifier hash matches\n    let computed_nullifier_hash = hash_1([nullifier]);\n    assert(computed_nullifier_hash == nullifier_hash, \"Nullifier hash mismatch\");\n}\n\nfn compute_merkle_root(\n    leaf: Field,\n    path: [Field; 20],\n    indices: [u1; 20],\n) -> Field {\n    let mut current = leaf;\n    for i in 0..20 {\n        \u002F\u002F u1 type enforces binary at compile time, no manual assert needed\n        let (left, right) = if indices[i] == 0 {\n            (current, path[i])\n        } else {\n            (path[i], current)\n        };\n        current = hash_2([left, right]);\n    }\n    current\n}\n```\n\n### Production Hardening: Domain Separation and Action Binding\n\nThe circuit above is the minimal pattern. Production apps should domain-separate hashes and bind the proof to a specific action. Commitments and nullifiers must use different domains.\n\nFor action-scoped apps such as voting, bind nullifier usage to an `external_nullifier` (for example `pollId`):\n\n```noir\nuse poseidon::poseidon::bn254::hash_2;\n\nfn main(\n    nullifier: Field,\n    secret: Field,\n    merkle_path: [Field; 20],\n    merkle_indices: [u1; 20],\n    merkle_root: pub Field,\n    external_nullifier: pub Field,\n    nullifier_hash: pub Field,\n) {\n    let note_secret = hash_2([nullifier, secret]);\n    let commitment = hash_2([1, note_secret]); \u002F\u002F 1 = commitment domain\n\n    let computed_root = compute_merkle_root(commitment, merkle_path, merkle_indices);\n    assert(computed_root == merkle_root, \"Merkle proof invalid\");\n\n    \u002F\u002F 2 = nullifier domain; external_nullifier scopes usage to a poll\u002Faction\n    let nullifier_domain = hash_2([2, external_nullifier]);\n    let computed_nullifier_hash = hash_2([nullifier_domain, nullifier]);\n    assert(computed_nullifier_hash == nullifier_hash, \"Nullifier hash mismatch\");\n}\n```\n\n### Solidity Contract Integration\n\nThe generated verifier contract is the source of truth. If you wrap it behind an interface like the one below, inspect the generated verifier ABI first and mirror it exactly, or add a dedicated adapter contract with a stable app-facing interface.\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\ninterface IVerifier {\n    function verify(bytes calldata proof, bytes32[] calldata publicInputs)\n        external view returns (bool);\n}\n\ncontract PrivacyPool {\n    IVerifier public immutable verifier;\n    bytes32 public merkleRoot;\n    mapping(bytes32 => bool) public usedNullifiers;\n\n    constructor(address _verifier) {\n        verifier = IVerifier(_verifier);\n    }\n\n    \u002F\u002F msg.sender is public — see \"same wallet\" warning above.\n    \u002F\u002F Only mutate state after verify() succeeds.\n    function act(bytes calldata _proof, bytes32 _merkleRoot, bytes32 _nullifierHash) external {\n        require(!usedNullifiers[_nullifierHash], \"Already acted\");\n        require(_merkleRoot == merkleRoot, \"Invalid root\");\n\n        \u002F\u002F Public inputs order MUST match the circuit's pub parameter order\n        bytes32[] memory publicInputs = new bytes32[](2);\n        publicInputs[0] = _merkleRoot;       \u002F\u002F pub merkle_root\n        publicInputs[1] = _nullifierHash;    \u002F\u002F pub nullifier_hash\n        require(verifier.verify(_proof, publicInputs), \"Invalid proof\");\n\n        \u002F\u002F Only mutate state after proof verification succeeds\n        usedNullifiers[_nullifierHash] = true;\n    }\n}\n```\n\n### Contract State Model\n\nFor a real app, the contract needs more than `merkleRoot` + `usedNullifiers`:\n\n- Emit an insert event with the commitment, leaf index, and resulting root\n- Store used nullifiers\n- Make the root-acceptance policy explicit: recent `knownRoots` or `currentRoot`-only\n- Verify proofs before success events, transfers\u002Fvotes, or nullifier writes\n\nGood default:\n\n```solidity\nevent CommitmentInserted(bytes32 indexed commitment, uint256 indexed leafIndex, bytes32 root);\n\nmapping(bytes32 => bool) public usedNullifiers;\nmapping(bytes32 => bool) public knownRoots; \u002F\u002F keep recent roots by default\nbytes32 public currentRoot;\n```\n\n**Root policy:** default to recent `knownRoots`. If you intentionally accept only `currentRoot`, say so explicitly and require clients to prove against the latest root.\n\nClients derive siblings by replaying `CommitmentInserted` into the offchain tree mirror; the contract never returns witness paths.\n\n### Onchain Commitment Storage (LeanIMT)\n\nMost Noir ZK apps store commitments in an onchain Merkle tree. If asked how commitments are stored onchain, name all three pieces: onchain `@zk-kit\u002Flean-imt.sol` + deployed `PoseidonT3`; offchain `@zk-kit\u002Flean-imt`; witness path from `tree.generateProof(leafIndex)`.\n\n**Solidity:**\n\n```bash\nnpm install @zk-kit\u002Flean-imt.sol\n```\n\n```solidity\nimport {LeanIMT, LeanIMTData} from \"@zk-kit\u002Flean-imt.sol\u002FLeanIMT.sol\";\n```\n\nDeploy `PoseidonT3` alongside; the tree contract uses it internally for hashing. The contract maintains the Merkle root automatically — users call `insert(commitment)`.\n\n**JavaScript (client-side tree mirror):**\n\n```bash\nnpm install @zk-kit\u002Flean-imt\n```\n```typescript\nimport { LeanIMT } from \"@zk-kit\u002Flean-imt\";\nconst { siblings, pathIndices } = tree.generateProof(leafIndex); \u002F\u002F after replaying CommitmentInserted events\n```\n---\n\n## Merkle Proof with zk-kit\n\nFor production Merkle trees, use the `@zk-kit.noir` library:\n\n```toml\n# Nargo.toml\n[dependencies]\nbinary_merkle_root = { tag = \"main\", git = \"https:\u002F\u002Fgithub.com\u002Fprivacy-scaling-explorations\u002Fzk-kit.noir\", directory = \"packages\u002Fbinary-merkle-root\" }\n```\n\n```noir\nuse binary_merkle_root::binary_merkle_root;\nuse poseidon::poseidon::bn254::hash_2;\n\nglobal TREE_DEPTH: u32 = 20;\n\nfn main(\n    leaf: Field,\n    indices: [u1; TREE_DEPTH],       \u002F\u002F u1 enforces binary, no manual assert needed\n    siblings: [Field; TREE_DEPTH],\n    root: pub Field,\n) {\n    let computed = binary_merkle_root(hash_2, leaf, TREE_DEPTH, indices, siblings);\n    assert(computed == root, \"Invalid Merkle proof\");\n}\n```\n\nThe function takes 5 args: `hasher`, `leaf`, `depth`, `indices`, `siblings`. The `indices` type is `[u1; MAX_DEPTH]` — the `u1` type constrains values to 0 or 1 at the type level, so you don't need manual binary assertions like `assert(indices[i] * (indices[i] - 1) == 0)`.\n\n---\n\n## Frontend Proof Generation (NoirJS)\n\nThe packages are `@noir-lang\u002Fnoir_js` + `@aztec\u002Fbb.js`. NOT `@noir-lang\u002Fbackend_barretenberg` (old, deprecated). The class is `UltraHonkBackend`, NOT `UltraPlonkBackend` (old).\n\n### Package Setup\n\n```bash\nnpm install @noir-lang\u002Fnoir_js \"@aztec\u002Fbb.js@$(bb --version)\"\n# ⚠ The @aztec\u002Fbb.js version must exactly match your bb CLI version (check with `bb --version`). A mismatch produces different proof serialization, causing onchain verification to fail.\n```\n\n### Vite Configuration\n\nNoirJS uses WASM and requires top-level await:\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig } from \"vite\";\nimport { nodePolyfills } from \"vite-plugin-node-polyfills\";\n\nexport default defineConfig({\n  plugins: [nodePolyfills()],\n  optimizeDeps: {\n    esbuildOptions: { target: \"esnext\" },\n  },\n  build: {\n    target: \"esnext\",\n  },\n});\n```\n\n### Next.js \u002F Scaffold-ETH 2 Configuration\n\n```typescript\n\u002F\u002F next.config.js\nconst nextConfig = {\n  webpack: (config) => {\n    config.experiments = { ...config.experiments, asyncWebAssembly: true };\n    return config;\n  },\n};\nmodule.exports = nextConfig;\n```\n\n```typescript\n\u002F\u002F components\u002FProofGenerator.tsx\n\"use client\";\nimport dynamic from \"next\u002Fdynamic\";\n\n\u002F\u002F All Noir components must be client-only — WASM doesn't run in SSR\nconst NoirProver = dynamic(() => import(\".\u002FNoirProver\"), { ssr: false });\n```\n\nCircuit artifact (`my_circuit.json`) must be copied to `public\u002F` and loaded via `fetch()` — cross-package JSON imports don't work in Next.js:\n\n```typescript\nconst circuit = await fetch(\"\u002Fmy_circuit.json\").then(r => r.json());\n```\n\n### Generating Proofs in the Browser\n\n```typescript\nimport { Noir } from \"@noir-lang\u002Fnoir_js\";\nimport { Barretenberg, UltraHonkBackend } from \"@aztec\u002Fbb.js\";\nimport circuit from \"..\u002Fcircuit\u002Ftarget\u002Fmy_circuit.json\";\n\n\u002F\u002F 1. Initialize Barretenberg instance, then backend and Noir\nconst bb = await Barretenberg.new();\nconst backend = new UltraHonkBackend(circuit.bytecode, bb);\nconst noir = new Noir(circuit);\n\n\u002F\u002F 2. Execute circuit (generates witness)\nconst inputs = {\n  nullifier: \"0x1234...\",\n  secret: \"0xabcd...\",\n  merkle_path: [\"0x...\", \"0x...\", ...],\n  merkle_indices: [0, 1, 0, ...],\n  merkle_root: \"0x...\",\n  nullifier_hash: \"0x...\",\n};\nconst { witness } = await noir.execute(inputs);\n\n\u002F\u002F 3. Generate proof — { keccak: true } matches --oracle_hash keccak used for the verifier\nconst proof = await backend.generateProof(witness, { keccak: true });\n\u002F\u002F proof.proof is Uint8Array — the raw proof bytes\n\u002F\u002F proof.publicInputs is string[] — the public inputs\n\nconst bytesToHex = (bytes: Uint8Array) =>\n  `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n\nconst toBytes32 = (field: string) =>\n  `0x${field.replace(\u002F^0x\u002F, \"\").padStart(64, \"0\")}` as `0x${string}`;\n\nconst proofHex = bytesToHex(proof.proof);\nconst publicInputs = proof.publicInputs.map(toBytes32);\n\n\u002F\u002F 4. Send to contract\nconst tx = await contract.act(\n  proofHex,                                 \u002F\u002F bytes calldata\n  publicInputs[0],                          \u002F\u002F merkle_root\n  publicInputs[1],                          \u002F\u002F nullifier_hash\n);\n```\n\n- `proof.proof` is `Uint8Array` — serialize it to `0x...` before sending over RPC\n- `proof.publicInputs` are strings — normalize them to 32-byte hex before comparing or passing to Solidity\n- EVM compatibility requires `--oracle_hash keccak` on CLI commands (see Build Pipeline above) AND `{ keccak: true }` in `generateProof()` — both must be set or you get serialization mismatches\n- Proof generation takes 5-30 seconds in browser depending on circuit size\n- Cleanup: call `bb.destroy()` when done\n- The generated verifier ABI is the source of truth; if your app uses an adapter, make the adapter match that ABI, not a guessed interface\n- **No `Buffer` in browser** — convert `Uint8Array` to hex directly\n\n### Serialization Boundary\n\nMost zk app failures happen here:\n\n- Circuit `pub` parameter order\n- NoirJS `proof.publicInputs` order\n- Solidity verifier input order\n- App contract wrapper\u002Fadaptor order\n\nThese four must match exactly.\n\nHard rule: inspect the generated verifier ABI and mirror it exactly. Do not assume every verifier exposes a generic `verify(bytes, bytes32[])` signature just because one example does.\n\n### Hash Parity Across Circuit, Tree, and Contract\n\nIf your circuit uses `poseidon::poseidon::bn254::hash_2`, then every other layer must use the same algorithm and input ordering:\n\n- commitment creation\n- Merkle parent hashing\n- offchain tree mirror\n- onchain tree contract\n\nDo not mix Poseidon, Poseidon2, and Keccak. `poseidon2Hash` is not a substitute for `poseidon::poseidon::bn254::hash_2`.\n\nBefore building the full app, test one leaf hash and one parent hash with known inputs across every layer and assert that the outputs match exactly.\n\n---\n\n## Chain Compatibility\n\nNoir\u002FBarretenberg proofs verify on any EVM chain with BN254 precompiles (ecAdd, ecMul, ecPairing at addresses 0x06-0x08).\n\n| Chain | Compatible | Notes |\n|-------|-----------|-------|\n| Ethereum mainnet | Yes | |\n| Optimism | Yes | |\n| Arbitrum | Yes | |\n| Base | Yes | |\n| Scroll | Yes | |\n| Polygon PoS | Yes | |\n| zkSync ERA | Yes | BN254 precompiles at standard addresses; implemented as smart contracts (higher gas) |\n| Polygon zkEVM | **No** | Being shut down — do not build on it |\n\n---\n\n## Circuit Security Checklist\n\n- [ ] All private inputs are constrained (no unconstrained witness values that could be manipulated)\n- [ ] Public inputs minimized — only what the verifier contract needs\n- [ ] Domain separation in hashes — different prefixes for commitments vs nullifiers (prevents cross-protocol replay)\n- [ ] Action-scoped apps bind nullifier usage to an `external_nullifier` \u002F `pollId` \u002F recipient \u002F action id\n- [ ] Nullifier prevents double-action (contract checks and stores used nullifier hashes)\n- [ ] Small-domain values not directly hashed as public outputs (if vote is 0 or 1, `hash(0)` and `hash(1)` are trivially brutable — add a salt)\n- [ ] Merkle tree depth matches between circuit (fixed at compile time) and contract\n- [ ] Merkle indices use `u1` type (enforces binary at compile time) — if using `Field`, manually constrain to 0\u002F1\n- [ ] Poseidon hash compatibility verified between Noir circuit, offchain tree mirror, and any onchain Poseidon library\n- [ ] The app persists notes (`nullifier`, `secret`, `commitment`, chain\u002Fcontract metadata, `leafIndex`)\n- [ ] The contract emits insert events with `leafIndex` and root so the client can rebuild the tree\n- [ ] The accepted-root policy is explicit (recent root history vs current-root-only)\n- [ ] The generated verifier ABI was inspected and mirrored exactly\n- [ ] Never deploy `MockVerifier`, even locally — deploy scripts and dev\u002Ftestnet wiring use the real `HonkVerifier`; `MockVerifier` is only for narrow unit tests\n\n---\n\n## Testing the App Core\n\nDo not stop at \"the circuit compiles.\" A working zk app needs tests at every boundary:\n\n1. **Circuit witness test** — fixed inputs should produce the expected public inputs and root checks.\n2. **Hash parity test** — the same leaf and parent inputs must hash identically in the circuit, offchain tree mirror, and onchain tree library.\n3. **Real-verifier integration test** — deploy the generated verifier and verify one real proof against it.\n4. **End-to-end app test** — insert a commitment, rebuild the tree from events, generate a browser\u002Fbackend proof, submit `act()`, and assert success.\n5. **Failure-path tests** — reused nullifier, wrong root, wrong sibling ordering, stale root, and mismatched public input order must all fail.\n\n`MockVerifier` is only for narrow unit tests. Deploy scripts, local dev wiring, and integration tests use the real generated `HonkVerifier`.\n\n---\n\n## AI Agent Tooling\n\nThis skill corrects common mistakes. For live, searchable access to Noir documentation, stdlib, and example circuits, agents can use the [noir-mcp-server](https:\u002F\u002Fgithub.com\u002Fcritesjosh\u002Fnoir-mcp-server):\n\n```bash\nclaude mcp add noir-mcp -- npx @critesjosh\u002Fnoir-mcp-server@latest\n```\n\nAfter adding the server, run `\u002Freload-plugins` so the new tools become available in the current session.\n\nIndexes the Noir compiler repo, standard library, examples, and community libraries (bignum, zk-kit.noir, etc.). Useful for looking up function signatures and browsing code beyond what this skill covers. If the npm package is unavailable, clone the repo and run directly.\n\nFor idiomatic, gate-efficient Noir style (hint-and-verify with `unconstrained`, ACIR vs Brillig tradeoffs, leveraging the type system, `assert_eq`, comparison costs), see the official noir-lang skill: [noir-idioms\u002FSKILL.md](https:\u002F\u002Fraw.githubusercontent.com\u002Fnoir-lang\u002Fnoir\u002Fmaster\u002F.claude\u002Fskills\u002Fnoir-idioms\u002FSKILL.md). This skill covers privacy-app architecture; that one covers writing efficient circuits.\n\n---\n\n## Example Repos and Building Blocks\n\nUse app-pattern repos for end-to-end architecture. Use primitives for narrow cryptographic building blocks.\n\n### App Patterns\n\n- **Simple private proof** — [noir-lang\u002Ftiny-noirjs-app](https:\u002F\u002Fgithub.com\u002Fnoir-lang\u002Ftiny-noirjs-app). Minimal NoirJS app for proving a private fact without a Merkle tree, nullifier, or signed-document flow. Good reference for age-threshold or balance-threshold style proofs.\n- **Anonymous voting** — [scaffold-eth\u002Fse-2-challenges (zk-voting branch)](https:\u002F\u002Fgithub.com\u002Fscaffold-eth\u002Fse-2-challenges\u002Ftree\u002Fchallenge-zk-voting). Full Scaffold-ETH 2 + Noir app: commitment-nullifier flow, LeanIMT membership proofs, Solidity verifier wiring, proof generation, and burner-wallet UX. [Challenge guide](https:\u002F\u002Fspeedrunethereum.com\u002Fchallenge\u002Fzk-voting).\n- **Private withdrawals \u002F mixer** — [Cyfrin\u002Fzk-mixer-cu](https:\u002F\u002Fgithub.com\u002FCyfrin\u002Fzk-mixer-cu). Direct Tornado-style Noir reference: deposit commitments into a Merkle tree, then withdraw with a membership proof and nullifier. Good for commitment-nullifier private withdrawal flows. Educational repo, not a production deployment reference.\n- **Private identity** — [zkpassport\u002Fcircuits](https:\u002F\u002Fgithub.com\u002Fzkpassport\u002Fcircuits). Selective-disclosure identity circuits: prove attributes like age or nationality without revealing the full credential.\n- **ZK email** — [zkemail\u002Fzkemail.nr](https:\u002F\u002Fgithub.com\u002Fzkemail\u002Fzkemail.nr). Email-auth proof system: DKIM verification plus selective disclosure of sender, subject, or body fragments without revealing the whole message.\n\n### Primitives\n\n- **Signature verification** — [colinnielsen\u002Fecrecover-noir](https:\u002F\u002Fgithub.com\u002Fcolinnielsen\u002Fecrecover-noir). Focused secp256k1 \u002F Ethereum signature recovery primitive for credentials, attestations, and account-linked proofs. Useful as a building block, not a full app architecture. Inspect the math and interface shape, but do not copy exact Noir syntax or package versions blindly.\n",{"name":5,"description":7},"dev","a004d0860ca4325bb3d3e925f501225c9181cc5a",".agents\u002Fskills\u002Fethskills\u002Fnoir",2,"https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest","https:\u002F\u002Fgithub.com\u002Fgrmkris","kris.gg","Software engineer","2026-10-30 17:18:59",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add grmkris\u002Fsidequest --skill noir",{"tool":39,"command":40},"bunx","bunx skills add grmkris\u002Fsidequest --skill noir",{"tool":42,"command":43},"pnpm","pnpm dlx skills add grmkris\u002Fsidequest --skill noir","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002F.agents\u002Fskills\u002Fethskills\u002Fnoir\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7DDXYENDQ276H5RRQMR2PXY","sidequest-worker","Find, activate and deliver paid Sidequest work through the hosted MCP connection for one registered agent.","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002Fskill\u002Fworker\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7DDXS0ABBE79S6WG3STCW1Q","sidequest-self-run","Use sidequest (Monad) from your own wallet over its REST API with SIWE, without MCP or a hosted agent. Use when an agent holds its own key and wants to hire or work on sidequest directly, sign its own transactions, or script the board.","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002Fskill\u002Fself-run\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7DDXN0XADEQ7PZ6021CTWAC","sidequest-publisher","Request quotes, publish allowance-funded hires, select workers and review paid work through hosted Sidequest MCP.","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002Fskill\u002Fpublisher\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7DDXH04WF73S9E5ZRMFC838","sidequest-connector","Connect a coding agent before an agent exists, create or select one through hosted MCP, then work or hire within signed permissions.","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002Fskill\u002Fconnector\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7DDXE7NFWNNDQ7WNFJNQS5J","sidequest-arbitrator","Rule on disputed sidequest (Monad) as the arbitrator, through the board's MCP server and the arbitrator key. Use when asked to arbitrate sidequest disputes, review a dispute bundle, or sign a ruling.","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002Fskill\u002Farbitrator\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":88,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7DDXBFNEYQNC3CMWM8QMRAS","wrangler","Run or troubleshoot Wrangler CLI commands and configure Worker projects for local development, Previews, deployment, and Cloudflare resource management.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002F.agents\u002Fskills\u002Fwrangler\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fgrmkris\u002Fsidequest\u002Fblob\u002Fdev\u002F.agents\u002Fskills\u002Fwrangler\u002FSKILL.md",[],[]]