Merge pull request #1 from waku-org/weboko/fe

feat: RLN interaction front-end
This commit is contained in:
Alvaro Revuelta 2023-11-01 10:53:13 +01:00 committed by GitHub
commit 26632559f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
40 changed files with 13285 additions and 0 deletions

3
.eslintrc.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

35
.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

8
Dockerfile Normal file
View File

@ -0,0 +1,8 @@
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "run", "serve"]

View File

@ -1,2 +1,32 @@
# waku-frontend
Waku's frontend. Interact with your waku node via this simple user interface
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
## To run independently
```bash
npm run build
npm run serve
```
## To run in docker
```bash
docker build -t waku_frontend .
docker run -d -p 3000:3000 -p waku_frontend
```

13
next.config.js Normal file
View File

@ -0,0 +1,13 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export",
webpack: (config) => {
config.externals.push({
"utf-8-validate": "commonjs utf-8-validate",
bufferutil: "commonjs bufferutil",
});
return config;
},
};
module.exports = nextConfig;

11868
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

36
package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "rln-js",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"serve": "serve ./out"
},
"dependencies": {
"@waku/rln": "0.1.1-7e8cb89",
"@waku/utils": "^0.0.12",
"ethers": "^5.7.2",
"next": "13.5.6",
"react": "^18",
"react-dom": "^18",
"uuid": "^9.0.1",
"zustand": "^4.4.4"
},
"devDependencies": {
"@metamask/types": "^1.1.0",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/uuid": "^9.0.6",
"autoprefixer": "^10",
"eslint": "^8",
"eslint-config-next": "13.5.6",
"postcss": "^8",
"serve": "^14.2.1",
"tailwindcss": "^3",
"typescript": "^5"
}
}

6
postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

1
public/next.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>

After

Width:  |  Height:  |  Size: 629 B

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

27
src/app/globals.css Normal file
View File

@ -0,0 +1,27 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}

View File

@ -0,0 +1,28 @@
import { Block, BlockTypes } from "@/components/Block";
import { Button } from "@/components/Button";
import { Subtitle } from "@/components/Subtitle";
import { useContract, useStore } from "@/hooks";
export const Blockchain: React.FunctionComponent<{}> = () => {
const { ethAccount, lastMembershipID } = useStore();
const { onFetchContract } = useContract();
return (
<Block className="mt-10">
<Block className="mb-3" type={BlockTypes.FlexHorizontal}>
<Subtitle>Contract</Subtitle>
<Button onClick={onFetchContract}>Fetch state</Button>
</Block>
<Block type={BlockTypes.FlexHorizontal}>
<p>Your address</p>
<code>{ethAccount || "Not loaded yet"}</code>
</Block>
<Block type={BlockTypes.FlexHorizontal}>
<p>Latest membership ID on contract</p>
<code>{lastMembershipID || "Not loaded yet"}</code>
</Block>
</Block>
);
};

View File

@ -0,0 +1,17 @@
import { Block, BlockTypes } from "@/components/Block";
import { Title } from "@/components/Title";
import { Status } from "@/components/Status";
import { useStore } from "@/hooks";
export const Header: React.FunctionComponent<{}> = () => {
const { appStatus } = useStore();
return (
<>
<Block className="mb-5" type={BlockTypes.FlexHorizontal}>
<Title>Waku RLN</Title>
</Block>
<Status text="Application status" mark={appStatus} />
</>
);
};

View File

@ -0,0 +1,158 @@
import React from "react";
import { Block, BlockTypes } from "@/components/Block";
import { Button } from "@/components/Button";
import { Subtitle } from "@/components/Subtitle";
import { useRLN, useStore, useWallet } from "@/hooks";
import { useKeystore } from "@/hooks/useKeystore";
export const Keystore: React.FunctionComponent<{}> = () => {
const { keystoreCredentials } = useStore();
const { onGenerateCredentials } = useWallet();
const { onReadCredentials, onRegisterCredentials } = useKeystore();
const { password, onPasswordChanged } = usePassword();
const { selectedKeystore, onKeystoreChanged } = useSelectedKeystore();
const { onExportKeystore, onImportKeystoreFileChange } =
useImportExportKeystore();
const credentialsNodes = React.useMemo(
() =>
keystoreCredentials.map((v) => (
<option key={v} value={v}>
{v}
</option>
)),
[keystoreCredentials]
);
return (
<Block className="mt-10">
<Block type={BlockTypes.FlexHorizontal}>
<Subtitle>Keystore</Subtitle>
<div>
<Button>
<label htmlFor="keystore-import" className="cursor-pointer">
Import
</label>
</Button>
<input
id="keystore-import"
type="file"
className="hidden"
onChange={onImportKeystoreFileChange}
/>
<Button className="ml-2" onClick={onExportKeystore}>
Export
</Button>
</div>
</Block>
<Block className="mt-4">
<label
htmlFor="keystore-input"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Password(used for reading/saving into Keystore)
</label>
<input
type="text"
value={password}
id="keystore-input"
onChange={onPasswordChanged}
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm w-full rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
/>
</Block>
<Block className="mt-4">
<p className="text-s mb-2">Generate new credentials from wallet</p>
<Button onClick={onGenerateCredentials}>
Generate new credentials
</Button>
<Button
className="ml-5"
onClick={() => onRegisterCredentials(password)}
>
Register credentials
</Button>
</Block>
<Block className="mt-4">
<p className="text-s">Read from Keystore</p>
<Block type={BlockTypes.FlexHorizontal}>
<select
value={selectedKeystore}
onChange={onKeystoreChanged}
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-3/4 p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
>
{credentialsNodes}
</select>
<Button onClick={() => onReadCredentials(selectedKeystore, password)}>
Read credentials
</Button>
</Block>
</Block>
</Block>
);
};
function usePassword() {
const [password, setPassword] = React.useState<string>("");
const onPasswordChanged = (event: React.FormEvent<HTMLInputElement>) => {
setPassword(event.currentTarget.value);
};
return {
password,
onPasswordChanged,
};
}
function useSelectedKeystore() {
const [selectedKeystore, setKeystore] = React.useState<string>("");
const onKeystoreChanged = (event: React.FormEvent<HTMLSelectElement>) => {
setKeystore(event.currentTarget.value || "");
};
return {
selectedKeystore,
onKeystoreChanged,
};
}
function useImportExportKeystore() {
const { rln } = useRLN();
const onExportKeystore = () => {
if (!rln) {
return;
}
const filename = "keystore.json";
const text = rln.keystore.toString();
const file = new File([text], filename, {
type: "application/json",
});
const link = document.createElement("a");
link.href = URL.createObjectURL(file);
link.download = filename;
link.click();
};
const onImportKeystoreFileChange = async (
event: React.FormEvent<HTMLInputElement>
) => {
const file = event.currentTarget?.files?.[0];
if (!file || !rln) {
return;
}
const text = await file.text();
rln.importKeystore(text);
};
return {
onExportKeystore,
onImportKeystoreFileChange,
};
}

View File

@ -0,0 +1,45 @@
import { Block, BlockTypes } from "@/components/Block";
import { useStore } from "@/hooks";
import { bytesToHex } from "@waku/utils/bytes";
export const KeystoreDetails: React.FunctionComponent<{}> = () => {
const { credentials, activeCredential, activeMembershipID } = useStore();
return (
<Block className="mt-5">
<Block className="mt-3" type={BlockTypes.FlexHorizontal}>
<p>Keystore hash</p>
<code>{activeCredential || "none"}</code>
</Block>
<Block className="mt-3" type={BlockTypes.FlexHorizontal}>
<p>Membership ID</p>
<code>{activeMembershipID || "none"}</code>
</Block>
<Block className="mt-3" type={BlockTypes.FlexHorizontal}>
<p>Secret Hash</p>
<code>{renderBytes(credentials?.IDSecretHash)}</code>
</Block>
<Block className="mt-3" type={BlockTypes.FlexHorizontal}>
<p>Commitment</p>
<code>{renderBytes(credentials?.IDCommitment)}</code>
</Block>
<Block className="mt-3" type={BlockTypes.FlexHorizontal}>
<p>Nullifier</p>
<code>{renderBytes(credentials?.IDNullifier)}</code>
</Block>
<Block className="mt-3" type={BlockTypes.FlexHorizontal}>
<p>Trapdoor</p>
<code>{renderBytes(credentials?.IDTrapdoor)}</code>
</Block>
</Block>
);
};
function renderBytes(bytes: undefined | Uint8Array): string {
return bytes ? bytesToHex(bytes) : "none";
}

View File

@ -0,0 +1,112 @@
import React from "react";
import { Block } from "@/components/Block";
import { Subtitle } from "@/components/Subtitle";
import { Button } from "@/components/Button";
import { MessageContent, useWaku } from "@/hooks";
export const Waku: React.FunctionComponent<{}> = () => {
const { onSend, messages } = useWaku();
const { nick, text, onNickChange, onMessageChange, resetText } = useMessage();
const onSendClick = async () => {
await onSend(nick, text);
resetText();
};
const renderedMessages = React.useMemo(
() => messages.map(renderMessage),
[messages]
);
return (
<Block className="mt-10">
<Subtitle>
Waku
</Subtitle>
<Block className="mt-4">
<label
htmlFor="nick-input"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Your nickname
</label>
<input
type="text"
id="nick-input"
placeholder="Choose a nickname"
value={nick}
onChange={onNickChange}
className="w-full mr-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
/>
</Block>
<Block className="mt-4">
<Block className="mb-2">
<label
htmlFor="message-input"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Message
</label>
<input
type="text"
id="message-input"
value={text}
onChange={onMessageChange}
placeholder="Text your message here"
className="w-full mr-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
/>
</Block>
<Button onClick={onSendClick}>Send</Button>
</Block>
<Block className="mt-8">
<p className="text-l mb-4">Messages</p>
<div>
<ul>{renderedMessages}</ul>
</div>
</Block>
</Block>
);
};
function useMessage() {
const [nick, setNick] = React.useState<string>("");
const [text, setText] = React.useState<string>("");
const onNickChange = (e: React.SyntheticEvent<HTMLInputElement>) => {
setNick(e.currentTarget.value || "");
};
const onMessageChange = (e: React.SyntheticEvent<HTMLInputElement>) => {
setText(e.currentTarget.value || "");
};
const resetText = () => {
setText("");
};
return {
nick,
text,
resetText,
onNickChange,
onMessageChange,
};
}
function renderMessage(content: MessageContent) {
return (
<li key={`${content.nick}-${content.time}`} className="mb-4">
<p>
<span className="text-lg">{content.nick}</span>
<span className="text-sm font-bold">
({content.time})
</span>
:
</p>
<p>{content.text}</p>
</li>
);
}

16
src/app/home/page.tsx Normal file
View File

@ -0,0 +1,16 @@
"use client";
import { Header } from "./components/Header";
import { Waku } from "./components/Waku";
import { Keystore } from "./components/Keystore";
import { KeystoreDetails } from "./components/KeystoreDetails";
export default function Home() {
return (
<main className="flex min-h-screen flex-col p-24 font-mono max-w-screen-lg m-auto">
<Header />
<Keystore />
<KeystoreDetails />
<Waku />
</main>
);
}

22
src/app/layout.tsx Normal file
View File

@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "RLN Example",
description: "Showcases RLN, Keystore and generation of proofs",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}

4
src/app/page.tsx Normal file
View File

@ -0,0 +1,4 @@
import Home from "@/app/home/page";
export const dynamic = "force-static";
export default Home;

23
src/components/Block.tsx Normal file
View File

@ -0,0 +1,23 @@
export enum BlockTypes {
FlexHorizontal = "flex-horizontal",
}
type BlockProps = {
children: any;
type?: BlockTypes;
className?: string;
};
export const Block: React.FunctionComponent<BlockProps> = (props) => {
const flexClassNames =
props.type === BlockTypes.FlexHorizontal
? "items-center justify-between lg:flex"
: "";
const restClassNames = props.className || "";
return (
<div className={`${flexClassNames} ${restClassNames}`}>
{props.children}
</div>
);
};

18
src/components/Button.tsx Normal file
View File

@ -0,0 +1,18 @@
type ButtonProps = {
children: any;
className?: string;
onClick?: (e?: any) => void;
};
export const Button: React.FunctionComponent<ButtonProps> = (props) => {
return (
<button
onClick={props.onClick}
className={`${
props.className || ""
} py-2.5 px-5 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:border-gray-600 dark:hover:text-white dark:hover:bg-gray-700`}
>
{props.children}
</button>
);
};

13
src/components/Status.tsx Normal file
View File

@ -0,0 +1,13 @@
type StatusProps = {
text: string;
mark: string;
};
export const Status: React.FunctionComponent<StatusProps> = (props) => (
<p className="text-s">
{props.text}:{" "}
<span className="underline underline-offset-3 decoration-4 decoration-blue-400 dark:decoration-blue-600">
{props.mark}
</span>
</p>
);

View File

@ -0,0 +1,8 @@
type SubtitleProps = {
children: any;
className?: string;
};
export const Subtitle: React.FunctionComponent<SubtitleProps> = (props) => (
<h2 className={`text-2xl ${props.className || ""}`}>{props.children}</h2>
);

8
src/components/Title.tsx Normal file
View File

@ -0,0 +1,8 @@
type TitleProps = {
children: any;
className?: string;
};
export const Title: React.FunctionComponent<TitleProps> = (props) => (
<h1 className={`text-4xl ${props.className || ""}`}>{props.children}</h1>
);

5
src/constants.ts Normal file
View File

@ -0,0 +1,5 @@
export const CONTENT_TOPIC = "/toy-chat/2/luzhou/proto";
export const PUBSUB_TOPIC = "/waku/2/default-waku/proto";
export const SIGNATURE_MESSAGE =
"The signature of this message will be used to generate your RLN credentials. Anyone accessing it may send messages on your behalf, please only share with the RLN dApp";

6
src/hooks/index.ts Normal file
View File

@ -0,0 +1,6 @@
export { useStore } from "./useStore";
export { useRLN } from "./useRLN";
export { useWallet } from "./useWallet";
export { useContract } from "./useContract";
export { useWaku } from "./useWaku";
export type { MessageContent } from "./useWaku";

60
src/hooks/useContract.ts Normal file
View File

@ -0,0 +1,60 @@
import React from "react";
import { useStore } from "./useStore";
import { useRLN } from "./useRLN";
type UseContractResult = {
onFetchContract: () => void;
};
export const useContract = (): UseContractResult => {
const { rln } = useRLN();
const { setEthAccount, setChainID, setLastMembershipID } = useStore();
const onFetchContract = React.useCallback(async () => {
const fetchAccounts = new Promise<void>(async (resolve) => {
if (!rln) {
console.log("Cannot fetch wallet, not provider found.");
resolve();
return;
}
try {
const accounts = await rln.ethProvider.send("eth_requestAccounts", []);
setEthAccount(accounts[0] || "");
const network = await rln.ethProvider.getNetwork();
setChainID(network.chainId);
} catch (error) {
console.error("Failed to connect to account: ", error);
}
resolve();
});
const fetchContract = new Promise<void>(async (resolve) => {
if (!rln?.rlnContract || !rln?.rlnInstance) {
console.log("Cannot fetch contract info, no contract found.");
resolve();
return;
}
try {
await rln.rlnContract.fetchMembers(rln.rlnInstance);
rln.rlnContract.subscribeToMembers(rln.rlnInstance);
const last = rln.rlnContract.members.at(-1);
if (last) {
setLastMembershipID(last.index.toNumber());
}
} catch (error) {
console.error("Failed to fetch contract state: ", error);
}
resolve();
});
await Promise.any([fetchAccounts, fetchContract]);
}, [rln, setEthAccount, setChainID, setLastMembershipID]);
return {
onFetchContract,
};
};

83
src/hooks/useKeystore.ts Normal file
View File

@ -0,0 +1,83 @@
import React from "react";
import { useStore } from "./useStore";
import { useRLN } from "./useRLN";
import { SEPOLIA_CONTRACT } from "@waku/rln";
import { StatusEventPayload } from "@/services/rln";
type UseKeystoreResult = {
onReadCredentials: (hash: string, password: string) => void;
onRegisterCredentials: (password: string) => void;
};
export const useKeystore = (): UseKeystoreResult => {
const { rln } = useRLN();
const {
credentials,
setActiveCredential,
setActiveMembershipID,
setAppStatus,
setCredentials,
} = useStore();
const onRegisterCredentials = React.useCallback(
async (password: string) => {
if (!credentials || !rln?.rlnContract || !password) {
return;
}
try {
setAppStatus(StatusEventPayload.CREDENTIALS_REGISTERING);
const membershipInfo = await rln.rlnContract.registerWithKey(
credentials
);
const membershipID = membershipInfo!.index.toNumber();
const keystoreHash = await rln.keystore.addCredential(
{
membership: {
treeIndex: membershipID,
chainId: SEPOLIA_CONTRACT.chainId,
address: SEPOLIA_CONTRACT.address,
},
identity: credentials,
},
password
);
setActiveCredential(keystoreHash);
setActiveMembershipID(membershipID);
rln.saveKeystore();
setAppStatus(StatusEventPayload.CREDENTIALS_REGISTERED);
} catch (error) {
setAppStatus(StatusEventPayload.CREDENTIALS_FAILURE);
console.error("Failed to register to RLN Contract: ", error);
return;
}
},
[credentials, rln, setActiveCredential, setActiveMembershipID, setAppStatus]
);
const onReadCredentials = React.useCallback(
async (hash: string, password: string) => {
if (!rln || !hash || !password) {
return;
}
try {
const record = await rln.keystore.readCredential(hash, password);
if (record) {
setCredentials(record.identity);
setActiveCredential(hash);
setActiveMembershipID(record.membership.treeIndex);
}
} catch (error) {
console.error("Failed to read credentials from Keystore.");
return;
}
},
[rln, setActiveCredential, setActiveMembershipID, setCredentials]
);
return {
onRegisterCredentials,
onReadCredentials,
};
};

50
src/hooks/useRLN.ts Normal file
View File

@ -0,0 +1,50 @@
"use client";
import React from "react";
import { rln, RLN, RLNEventsNames } from "@/services/rln";
import { useStore } from "./useStore";
type RLNResult = {
rln: undefined | RLN;
};
export const useRLN = (): RLNResult => {
const { setAppStatus, setKeystoreCredentials } = useStore();
const rlnRef = React.useRef<undefined | RLN>(undefined);
React.useEffect(() => {
if (rlnRef.current || !rln) {
return;
}
let terminate = false;
const statusListener = (event: CustomEvent) => {
setAppStatus(event?.detail);
};
rln.addEventListener(RLNEventsNames.Status, statusListener);
const keystoreListener = (event: CustomEvent) => {
setKeystoreCredentials(event?.detail || []);
};
rln.addEventListener(RLNEventsNames.Keystore, keystoreListener);
const run = async () => {
if (terminate) {
return;
}
await rln?.init();
rlnRef.current = rln;
};
run();
return () => {
terminate = true;
rln?.removeEventListener(RLNEventsNames.Status, statusListener);
rln?.removeEventListener(RLNEventsNames.Keystore, keystoreListener);
};
}, [rlnRef, setAppStatus]);
return {
rln: rlnRef.current,
};
};

68
src/hooks/useStore.ts Normal file
View File

@ -0,0 +1,68 @@
import { create } from "zustand";
import { IdentityCredential } from "@waku/rln";
type StoreResult = {
appStatus: string;
setAppStatus: (v: string) => void;
ethAccount: string;
setEthAccount: (v: string) => void;
chainID: undefined | number;
setChainID: (v: number) => void;
lastMembershipID: undefined | number;
setLastMembershipID: (v: number) => void;
credentials: undefined | IdentityCredential;
setCredentials: (v: undefined | IdentityCredential) => void;
activeCredential: string;
keystoreCredentials: string[];
setKeystoreCredentials: (v: string[]) => void;
setActiveCredential: (v: string) => void;
activeMembershipID: undefined | number;
setActiveMembershipID: (v: number) => void;
wakuStatus: string;
setWakuStatus: (v: string) => void;
};
const DEFAULT_VALUE = "none";
export const useStore = create<StoreResult>((set) => {
const generalModule = {
appStatus: DEFAULT_VALUE,
setAppStatus: (v: string) => set((state) => ({ ...state, appStatus: v })),
ethAccount: "",
setEthAccount: (v: string) => set((state) => ({ ...state, ethAccount: v })),
chainID: undefined,
setChainID: (v: number) => set((state) => ({ ...state, chainID: v })),
lastMembershipID: undefined,
setLastMembershipID: (v: number) =>
set((state) => ({ ...state, lastMembershipID: v })),
credentials: undefined,
setCredentials: (v: undefined | IdentityCredential) =>
set((state) => ({ ...state, credentials: v })),
};
const wakuModule = {
wakuStatus: DEFAULT_VALUE,
setWakuStatus: (v: string) => set((state) => ({ ...state, wakuStatus: v })),
};
const keystoreModule = {
activeCredential: DEFAULT_VALUE,
setActiveCredential: (v: string) =>
set((state) => ({ ...state, activeCredential: v })),
keystoreCredentials: [],
setKeystoreCredentials: (v: string[]) =>
set((state) => ({ ...state, keystoreCredentials: v })),
activeMembershipID: undefined,
setActiveMembershipID: (v: number) =>
set((state) => ({ ...state, activeMembershipID: v })),
};
return {
...generalModule,
...wakuModule,
...keystoreModule,
};
});

55
src/hooks/useWaku.ts Normal file
View File

@ -0,0 +1,55 @@
import React from "react";
import { CONTENT_TOPIC } from "@/constants";
import { Message, waku } from "@/services/waku";
export type MessageContent = {
nick: string;
text: string;
time: string;
};
export const useWaku = () => {
const [messages, setMessages] = React.useState<MessageContent[]>([]);
React.useEffect(() => {
const messageListener = (event: CustomEvent) => {
const messages: Message[] = event.detail;
const parsedMessaged = messages.map((message) => {
const time = new Date(message.timestamp);
const payload = JSON.parse(atob(message.payload));
return {
nick: payload?.nick || "unknown",
text: payload?.text || "empty",
time: time.toDateString(),
};
});
setMessages((prev) => [...prev, ...parsedMessaged]);
};
waku.filter.addEventListener(CONTENT_TOPIC, messageListener);
return () => {
waku.filter.removeEventListener(CONTENT_TOPIC, messageListener);
};
}, [setMessages]);
const onSend = React.useCallback(
async (nick: string, text: string) => {
await waku.lightPush.send({
version: 0,
timestamp: Date.now(),
contentTopic: CONTENT_TOPIC,
payload: btoa(JSON.stringify({
nick,
text
})),
});
},
[]
);
return { onSend, messages };
};

62
src/hooks/useWallet.ts Normal file
View File

@ -0,0 +1,62 @@
import React from "react";
import { useStore } from "./useStore";
import { isEthereumEvenEmitterValid } from "@/utils/ethereum";
import { useRLN } from "./useRLN";
import { SIGNATURE_MESSAGE } from "@/constants";
type UseWalletResult = {
onGenerateCredentials: () => void;
};
export const useWallet = (): UseWalletResult => {
const { rln } = useRLN();
const { setEthAccount, setChainID, setCredentials } = useStore();
React.useEffect(() => {
const ethereum = window.ethereum;
if (!isEthereumEvenEmitterValid(ethereum)) {
console.log("Cannot subscribe to ethereum events.");
return;
}
const onAccountsChanged = (accounts: string[]) => {
setEthAccount(accounts[0] || "");
};
ethereum.on("accountsChanged", onAccountsChanged);
const onChainChanged = (chainID: string) => {
const ID = parseInt(chainID, 16);
setChainID(ID);
};
ethereum.on("chainChanged", onChainChanged);
return () => {
ethereum.removeListener("chainChanged", onChainChanged);
ethereum.removeListener("accountsChanged", onAccountsChanged);
};
}, [setEthAccount, setChainID]);
const onGenerateCredentials = React.useCallback(async () => {
if (!rln?.ethProvider) {
console.log("Cannot generate credentials, no provider found.");
return;
}
const signer = rln.ethProvider.getSigner();
const signature = await signer.signMessage(
`${SIGNATURE_MESSAGE}. Nonce: ${randomNumber()}`
);
const credentials = await rln.rlnInstance?.generateSeededIdentityCredential(
signature
);
setCredentials(credentials);
}, [rln, setCredentials]);
return {
onGenerateCredentials,
};
};
function randomNumber(): number {
return Math.ceil(Math.random() * 1000);
}

14
src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1,14 @@
/// <reference types="react-scripts" />
type EthereumEvents = "accountsChanged" | "chainChanged";
type EthereumEventListener = (v: any) => void;
type Ethereum = {
request: () => void;
on: (name: EthereumEvents, fn: EthereumEventListener) => void;
removeListener: (name: EthereumEvents, fn: EthereumEventListener) => void;
};
interface Window {
ethereum: Ethereum;
}

147
src/services/rln.ts Normal file
View File

@ -0,0 +1,147 @@
import { ethers } from "ethers";
import {
create,
Keystore,
RLNContract,
SEPOLIA_CONTRACT,
RLNInstance,
} from "@waku/rln";
import { isBrowserProviderValid } from "@/utils/ethereum";
export enum RLNEventsNames {
Status = "status",
Keystore = "keystore-changed",
}
export enum StatusEventPayload {
WASM_LOADING = "WASM Blob download in progress...",
WASM_FAILED = "Failed to download WASM, check console",
CONTRACT_LOADING = "Connecting to RLN contract",
CONTRACT_FAILED = "Failed to connect to RLN contract",
RLN_INITIALIZED = "RLN dependencies initialized",
KEYSTORE_LOCAL = "Keystore initialized from localStore",
KEYSTORE_NEW = "New Keystore was initialized",
CREDENTIALS_REGISTERING = "Registering credentials...",
CREDENTIALS_REGISTERED = "Registered credentials",
CREDENTIALS_FAILURE = "Failed to register credentials, check console",
}
type EventListener = (event: CustomEvent) => void;
type IRLN = {
saveKeystore: () => void;
addEventListener: (name: RLNEventsNames, fn: EventListener) => void;
removeEventListener: (name: RLNEventsNames, fn: EventListener) => void;
};
export class RLN implements IRLN {
private readonly emitter = new EventTarget();
public readonly ethProvider: ethers.providers.Web3Provider;
public rlnInstance: undefined | RLNInstance;
public rlnContract: undefined | RLNContract;
public keystore: Keystore;
private initialized = false;
private initializing = false;
public constructor() {
const ethereum =
window.ethereum as unknown as ethers.providers.ExternalProvider;
if (!isBrowserProviderValid(ethereum)) {
throw Error(
"Invalid Ethereum provider present on the page. Check if MetaMask is connected."
);
}
this.ethProvider = new ethers.providers.Web3Provider(ethereum, "any");
this.keystore = this.initKeystore();
}
public async init(): Promise<void> {
if (this.initialized || this.initializing) {
return;
}
this.initializing = true;
const rlnInstance = await this.initRLNWasm();
await this.initRLNContract(rlnInstance);
this.emitStatusEvent(StatusEventPayload.RLN_INITIALIZED);
// emit keystore keys once app is ready
this.emitKeystoreKeys();
this.initialized = true;
this.initializing = false;
}
private async initRLNWasm(): Promise<RLNInstance> {
this.emitStatusEvent(StatusEventPayload.WASM_LOADING);
try {
this.rlnInstance = await create();
return this.rlnInstance;
} catch (error) {
console.error(
"Failed at fetching WASM and creating RLN instance: ",
error
);
this.emitStatusEvent(StatusEventPayload.WASM_FAILED);
throw error;
}
}
private async initRLNContract(rlnInstance: RLNInstance): Promise<void> {
this.emitStatusEvent(StatusEventPayload.CONTRACT_LOADING);
try {
this.rlnContract = await RLNContract.init(rlnInstance, {
registryAddress: SEPOLIA_CONTRACT.address,
provider: this.ethProvider.getSigner(),
});
} catch (error) {
console.error("Failed to connect to RLN contract: ", error);
this.emitStatusEvent(StatusEventPayload.CONTRACT_FAILED);
throw error;
}
}
private initKeystore(): Keystore {
const localKeystoreString = localStorage.getItem("keystore");
const _keystore = Keystore.fromString(localKeystoreString || "");
return _keystore || Keystore.create();
}
public addEventListener(name: RLNEventsNames, fn: EventListener) {
return this.emitter.addEventListener(name, fn as any);
}
public removeEventListener(name: RLNEventsNames, fn: EventListener) {
return this.emitter.removeEventListener(name, fn as any);
}
private emitStatusEvent(payload: StatusEventPayload) {
this.emitter.dispatchEvent(
new CustomEvent(RLNEventsNames.Status, { detail: payload })
);
}
private emitKeystoreKeys() {
const credentials = Object.keys(this.keystore.toObject().credentials || {});
this.emitter.dispatchEvent(
new CustomEvent(RLNEventsNames.Keystore, { detail: credentials })
);
}
public async saveKeystore() {
localStorage.setItem("keystore", this.keystore.toString());
this.emitKeystoreKeys();
}
public importKeystore(value: string) {
this.keystore = Keystore.fromString(value) || Keystore.create();
this.saveKeystore();
}
}
// Next.js sometimes executes code in server env where there is no window object
export const rln = typeof window === "undefined" ? undefined : new RLN();

140
src/services/waku.ts Normal file
View File

@ -0,0 +1,140 @@
import { v4 as uuid } from "uuid";
import {
PUBSUB_TOPIC,
} from "@/constants";
import { http } from "@/utils/http";
export type Message = {
payload: string,
contentTopic: string,
version: number,
timestamp: number
};
type EventListener = (event: CustomEvent) => void;
const SECOND = 1000;
const LOCAL_NODE = "http://127.0.0.1:8645/";
const FILTER_URL = "/filter/v2/";
const LIGHT_PUSH = "/lightpush/v1/";
class Filter {
private readonly internalEmitter = new EventTarget();
private readonly subscriptionsEmitter = new EventTarget();
private contentTopicToRequestID: Map<string, string> = new Map();
private contentTopicListeners: Map<string, number> = new Map();
// only one content topic subscriptions is possible now
private subscriptionRoutine: undefined | number;
constructor() {
this.internalEmitter.addEventListener("subscribed", this.handleSubscribed.bind(this));
this.internalEmitter.addEventListener("unsubscribed", this.handleUnsubscribed.bind(this));
}
private async handleSubscribed(_e: Event) {
const event = _e as CustomEvent;
const contentTopic = event.detail;
const numberOfListeners = this.contentTopicListeners.get(contentTopic);
// if nwaku node already subscribed to this content topic
if (numberOfListeners) {
this.contentTopicListeners.set(contentTopic, numberOfListeners + 1);
return;
}
const requestId = uuid();
await http.post(`${LOCAL_NODE}/${FILTER_URL}/subscriptions`, {
requestId,
contentFilters: [contentTopic],
pubsubTopic: PUBSUB_TOPIC
});
this.subscriptionRoutine = window.setInterval(async () => {
await this.fetchMessages();
}, SECOND);
this.contentTopicToRequestID.set(contentTopic, requestId);
this.contentTopicListeners.set(contentTopic, 1);
}
private async handleUnsubscribed(_e: Event) {
const event = _e as CustomEvent;
const contentTopic = event.detail;
const requestId = this.contentTopicToRequestID.get(contentTopic);
const numberOfListeners = this.contentTopicListeners.get(contentTopic);
if (!numberOfListeners || !requestId) {
return;
}
if (numberOfListeners - 1 > 0) {
this.contentTopicListeners.set(contentTopic, numberOfListeners - 1);
return;
}
await http.delete(`${LOCAL_NODE}/${FILTER_URL}/subscriptions`, {
requestId,
contentFilters: [contentTopic],
pubsubTopic: PUBSUB_TOPIC
});
clearInterval(this.subscriptionRoutine);
this.contentTopicListeners.delete(contentTopic);
this.contentTopicToRequestID.delete(contentTopic);
}
private async fetchMessages(): Promise<void> {
const contentTopic = Object.keys(this.contentTopicListeners)[0];
if (!contentTopic) {
return;
}
const response = await http.get(`${LOCAL_NODE}/${FILTER_URL}/${encodeURIComponent(contentTopic)}`);
const body: Message[] = await response.json();
if (!body || !body.length) {
return;
}
this.subscriptionsEmitter.dispatchEvent(
new CustomEvent(contentTopic, { detail: body })
);
}
public addEventListener(contentTopic: string, fn: EventListener) {
this.emitSubscribedEvent(contentTopic);
return this.subscriptionsEmitter.addEventListener(contentTopic, fn as any);
}
public removeEventListener(contentTopic: string, fn: EventListener) {
this.emitUnsubscribedEvent(contentTopic);
return this.subscriptionsEmitter.removeEventListener(contentTopic, fn as any);
}
private emitSubscribedEvent(contentTopic: string) {
this.internalEmitter.dispatchEvent(new CustomEvent("subscribed", { detail: contentTopic }));
}
private emitUnsubscribedEvent(contentTopic: string) {
this.internalEmitter.dispatchEvent(new CustomEvent("unsubscribed", { detail: contentTopic }));
}
}
class LightPush {
constructor() {}
public async send(message: Message): Promise<void> {
await http.post(`${LOCAL_NODE}/${LIGHT_PUSH}/message`, {
pubsubTopic: PUBSUB_TOPIC,
message,
});
}
}
export const waku = {
filter: new Filter(),
lightPush: new LightPush(),
};

17
src/utils/ethereum.ts Normal file
View File

@ -0,0 +1,17 @@
export const isBrowserProviderValid = (obj: any): boolean => {
if (obj && typeof obj.request === "function") {
return true;
}
return false;
};
export const isEthereumEvenEmitterValid = (obj: any): boolean => {
if (
obj &&
typeof obj.on === "function" &&
typeof obj.removeListener === "function"
) {
return true;
}
return false;
};

31
src/utils/http.ts Normal file
View File

@ -0,0 +1,31 @@
export const http = {
post(url: string, body: any) {
return fetch(new URL(url), {
method: "POST",
mode: "no-cors",
referrerPolicy: "no-referrer",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(body)
});
},
delete(url: string, body: any) {
return fetch(new URL(url), {
method: "DELETE",
mode: "no-cors",
referrerPolicy: "no-referrer",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(body)
});
},
get(url: string) {
return fetch(new URL(url));
}
};

20
tailwind.config.ts Normal file
View File

@ -0,0 +1,20 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
};
export default config;

27
tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}