Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating to 0.23.0 #73

Merged
merged 19 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 16 additions & 20 deletions vite-hardhat/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ Want to get started in a pinch? Start your project in a free Github Codespace!
In the meantime, follow these simple steps to work on your own machine:

1. Install [yarn](https://yarnpkg.com/) (tested on yarn v1.22.19)

2. Install [Node.js >20.10 (latest LTS)](https://nodejs.org/en) (tested on v18.17.0)

3. Install [noirup](https://noir-lang.org/docs/getting_started/installation/#installing-noirup) with

```bash
Expand Down Expand Up @@ -46,13 +44,11 @@ cd circuits
nargo codegen-verifier
```

A file named `plonk_vk.sol` should appear in the `circuits/contracts/with_foundry` folder.
A file named `plonk_vk.sol` should appear in the `circuit/contracts/noirstarter` folder.

### Test locally

1. Copy `vite-hardhat/.env.example` to a new file `vite-hardhat/.env`.

2. Start a local development EVM at <http://localhost:8545> with
1. Start a local development EVM at <http://localhost:8545> with

```bash
npx hardhat node
Expand All @@ -64,7 +60,7 @@ A file named `plonk_vk.sol` should appear in the `circuits/contracts/with_foundr
anvil
```

3. Run the [example test file](./test/index.test.ts) with
2. Run the [example test file](./test/index.test.ts) with

```bash
yarn test
Expand All @@ -91,29 +87,29 @@ The test demonstrates basic usage of Noir in a TypeScript Node.js environment.
3. Build the project and deploy contracts to the local development chain with

```bash
NETWORK=localhost yarn build
yarn build
```

> **Note:** If the deployment fails, try removing `yarn.lock` and reinstalling dependencies with
> `yarn`.

4. Once your contracts are deployed and the build is finished, you can preview the built website with

```bash
yarn preview
```

### Deploy on networks
### Deploy on testnets

For convenience, we added two configurations for deployment on various testnets. You can find them in `hardhat.config.cts`.

You can choose any other network in `hardhat.config.ts` and deploy there using this `NETWORK`
environment variable.
To deploy on these testnets, copy the `.env.example` and add your own [alchemy](https://www.alchemy.com/) keys for these networks.

For example, `NETWORK=mumbai yarn build` or `NETWORK=sepolia yarn build`.
Then, prepend your commands with your desired network in a `NETWORK` environment variable. For example, to deploy on sepolia:

Make sure you:
```bash
NETWORK=sepolia yarn build`
```

- Update the deployer private keys in `vite-hardhat/.env`
- Have funds in the deployer account
- Add keys for alchemy (to act as a node) in `vite-hardhat/.env`
Feel free to add more networks, just make sure you:

Feel free to contribute with other networks in `hardhat.config.ts`
- Add deployer private keys and alchemy API keys in `vite-hardhat/.env`
- Have funds in these accounts
- Add a configuration in `hardhat.config.cts`
File renamed without changes.

Large diffs are not rendered by default.

File renamed without changes.
3 changes: 0 additions & 3 deletions vite-hardhat/circuits/Prover.toml

This file was deleted.

2 changes: 0 additions & 2 deletions vite-hardhat/circuits/Verifier.toml

This file was deleted.

143 changes: 20 additions & 123 deletions vite-hardhat/components/index.tsx
Original file line number Diff line number Diff line change
@@ -1,139 +1,36 @@
import {
useState,
useEffect,
SetStateAction,
ReactEventHandler,
FormEvent,
ChangeEvent,
} from 'react';

import { toast } from 'react-toastify';
import { useState } from 'react';
import React from 'react';

import { Noir } from '@noir-lang/noir_js';
import { BarretenbergBackend, flattenPublicInputs } from '@noir-lang/backend_barretenberg';
import { CompiledCircuit, ProofData } from '@noir-lang/types';
import { compile, PathToFileSourceMap } from '@noir-lang/noir_wasm';

import { useAccount, useConnect, useContractWrite } from 'wagmi';
import { contractCallConfig } from '../utils/wagmi.jsx';
import { bytesToHex } from 'viem';

async function getCircuit(name: string) {
const res = await fetch(new URL('../circuits/src/main.nr', import.meta.url));
const noirSource = await res.text();

const sourceMap = new PathToFileSourceMap();
sourceMap.add_source_code('main.nr', noirSource);
const compiled = compile('main.nr', undefined, undefined, sourceMap);
return compiled;
}
import { useOnChainVerification } from '../hooks/useOnChainVerification.jsx';
import { useProofGeneration } from '../hooks/useProofGeneration.jsx';
import { useOffChainVerification } from '../hooks/useOffChainVerification.jsx';

function Component() {
const [input, setInput] = useState({ x: 0, y: 0 });
const [proof, setProof] = useState<ProofData>();
const [noir, setNoir] = useState<Noir | null>(null);
const [backend, setBackend] = useState<BarretenbergBackend | null>(null);
const [input, setInput] = useState<{ x: string; y: string } | undefined>();
const { noir, proofData } = useProofGeneration(input);
useOffChainVerification(noir, proofData);
useOnChainVerification(proofData);

const { isConnected } = useAccount();
const { connect, connectors } = useConnect();

const { write, data, error, isLoading, isError } = useContractWrite({
...contractCallConfig,
functionName: 'verify',
});

// Handles input state
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const submit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (e.target) setInput({ ...input, [e.target.name]: e.target.value });
};

// Calculates proof
const calculateProof = async () => {
const calc = new Promise(async (resolve, reject) => {
const { proof, publicInputs } = await noir!.generateFinalProof(input);
console.log('Proof created: ', proof);
setProof({ proof, publicInputs });
resolve(proof);
});
toast.promise(calc, {
pending: 'Calculating proof...',
success: 'Proof calculated!',
error: 'Error calculating proof',
});
};
const elements = e.currentTarget.elements;
if (!elements) return;

const verifyProof = async () => {
const verifyOffChain = new Promise(async (resolve, reject) => {
if (proof) {
const verification = await noir!.verifyFinalProof({
proof: proof.proof,
publicInputs: proof.publicInputs,
});
console.log('Proof verified: ', verification);
resolve(verification);
}
});
const x = elements.namedItem('x') as HTMLInputElement;
const y = elements.namedItem('y') as HTMLInputElement;

toast.promise(verifyOffChain, {
pending: 'Verifying proof off-chain...',
success: 'Proof verified off-chain!',
error: 'Error verifying proof',
});

connectors.map(c => c.ready && connect({ connector: c }));

if (proof) {
write?.({
args: [bytesToHex(proof.proof), flattenPublicInputs(proof.publicInputs)],
});
}
setInput({ x: x.value, y: y.value });
};

useEffect(() => {
if (proof) {
verifyProof();
return () => {
backend!.destroy();
};
}
}, [proof]);

useEffect(() => {
if (data) toast.success('Proof verified on-chain!');
}, [data]);

const initNoir = async () => {
const circuit = await getCircuit('main');

// @ts-ignore
const backend = new BarretenbergBackend(circuit.program, { threads: 8 });
setBackend(backend);

// @ts-ignore
const noir = new Noir(circuit.program, backend);
await toast.promise(noir.init(), {
pending: 'Initializing Noir...',
success: 'Noir initialized!',
error: 'Error initializing Noir',
});
setNoir(noir);
};

useEffect(() => {
initNoir();
}, []);

return (
<div className="container">
<form className="container" onSubmit={submit}>
<h1>Example starter</h1>
<h2>This circuit checks that x and y are different</h2>
<h2>This circuit checks that x and y are different (yey!)</h2>
<p>Try it!</p>
<input name="x" type={'number'} onChange={handleChange} value={input.x} />
<input name="y" type={'number'} onChange={handleChange} value={input.y} />
<button onClick={calculateProof}>Calculate proof</button>
</div>
<input name="x" type="text" />
<input name="y" type="text" />
<button type="submit">Calculate proof</button>
</form>
);
}

Expand Down
2 changes: 1 addition & 1 deletion vite-hardhat/hardhat.config.cts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const config: HardhatUserConfig = {
},
},
paths: {
sources: './circuits/contract/noirstarter',
sources: './circuit',
},
};

Expand Down
19 changes: 19 additions & 0 deletions vite-hardhat/hooks/useOffChainVerification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use client';

import { ProofData } from '@noir-lang/types';
import { useEffect } from 'react';
import { toast } from 'react-toastify';
import { BarretenbergBackend } from '@noir-lang/backend_barretenberg';
import { Noir } from '@noir-lang/noir_js';

export function useOffChainVerification(noir?: Noir, proofData?: ProofData) {
useEffect(() => {
if (!proofData || !noir) return;

toast.promise(noir.verifyFinalProof(proofData), {
pending: 'Verifying proof off-chain',
success: 'Proof verified off-chain',
error: 'Error verifying proof off-chain',
});
}, [proofData]);
}
57 changes: 57 additions & 0 deletions vite-hardhat/hooks/useOnChainVerification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ProofData } from '@noir-lang/types';
import { useAccount, useConnect, useContractRead } from 'wagmi';
import { contractCallConfig } from '../utils/wagmi.jsx';
import { bytesToHex } from 'viem';
import { useEffect, useState } from 'react';
import { Id, toast } from 'react-toastify';

export function useOnChainVerification(proofData?: ProofData) {
const { connect, connectors } = useConnect();
const { isConnected } = useAccount();
const [args, setArgs] = useState<[string, string[]] | undefined>();

const { data, error } = useContractRead({
...contractCallConfig,
functionName: 'verify',
args,
});

const [onChainToast, setOnChainToast] = useState<Id>(0);

useEffect(() => {
if (!isConnected) {
console.log("not connected, won't attempt on-chain verification");
}
if (!proofData || !isConnected) {
return;
}

setArgs([bytesToHex(proofData.proof), proofData.publicInputs]);

if (!onChainToast)
setOnChainToast(toast.loading('Verifying proof on-chain', { autoClose: 10000 }));
}, [proofData]);

useEffect(() => {
if (!isConnected) {
connectors.map(c => c.ready && connect({ connector: c }));
}
}, [isConnected]);

useEffect(() => {
if (data) {
toast.update(onChainToast, {
type: 'success',
render: 'Proof verified on-chain!',
isLoading: false,
});
} else if (error) {
toast.update(onChainToast, {
type: 'error',
render: 'Error verifying proof on-chain!',
isLoading: false,
});
console.error(error);
}
}, [data, error]);
}
39 changes: 39 additions & 0 deletions vite-hardhat/hooks/useProofGeneration.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { toast } from 'react-toastify';
import { useEffect, useState } from 'react';
import { getCircuit } from '../utils/compile.js';
import { BarretenbergBackend, ProofData } from '@noir-lang/backend_barretenberg';
import { Noir } from '@noir-lang/noir_js';

export function useProofGeneration(inputs?: { [key: string]: string }) {
const [proofData, setProofData] = useState<ProofData | undefined>();
const [noir, setNoir] = useState<Noir | undefined>();

const proofGeneration = async () => {
if (!inputs) return;
const circuit = await getCircuit();
const backend = new BarretenbergBackend(circuit, { threads: navigator.hardwareConcurrency });
const noir = new Noir(circuit, backend);

await toast.promise(noir.init, {
pending: 'Initializing Noir...',
success: 'Noir initialized!',
error: 'Error initializing Noir',
});

const data = await toast.promise(noir.generateFinalProof(inputs), {
pending: 'Generating proof',
success: 'Proof generated',
error: 'Error generating proof',
});

setProofData(data);
setNoir(noir);
};

useEffect(() => {
if (!inputs) return;
proofGeneration();
}, [inputs]);

return { noir, proofData };
}
6 changes: 0 additions & 6 deletions vite-hardhat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import './App.css';
import 'react-toastify/dist/ReactToastify.css';
import { ToastContainer } from 'react-toastify';
import Component from './components/index';

import initNoirWasm from '@noir-lang/noir_wasm';
import initNoirC from '@noir-lang/noirc_abi';
import initACVM from '@noir-lang/acvm_js';
import { WagmiConfig } from 'wagmi';
Expand All @@ -16,9 +14,6 @@ const InitWasm = ({ children }) => {
useEffect(() => {
(async () => {
await Promise.all([
initNoirWasm(
new URL('@noir-lang/noir_wasm/web/noir_wasm_bg.wasm', import.meta.url).toString(),
),
initACVM(new URL('@noir-lang/acvm_js/web/acvm_js_bg.wasm', import.meta.url).toString()),
initNoirC(
new URL('@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm', import.meta.url).toString(),
Expand All @@ -43,6 +38,5 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
<Component />
<ToastContainer />
</InitWasm>
,
</Providers>,
);
Loading
Loading