copy rln-js

This commit is contained in:
Sasha 2023-10-30 23:57:10 +01:00
parent 9544cc1502
commit 249f678ab5
No known key found for this signature in database
38 changed files with 16697 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

View File

@ -1,2 +1,25 @@
# 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
```

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;

15230
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
package.json Normal file
View File

@ -0,0 +1,37 @@
{
"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/sdk": "^0.0.20",
"@waku/utils": "^0.0.12",
"ethers": "^5.7.2",
"multiaddr": "^10.0.1",
"next": "13.5.6",
"protobufjs": "^7.2.5",
"react": "^18",
"react-dom": "^18",
"zustand": "^4.4.4"
},
"devDependencies": {
"@metamask/types": "^1.1.0",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"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,117 @@
import React from "react";
import { Block } from "@/components/Block";
import { Subtitle } from "@/components/Subtitle";
import { Status } from "@/components/Status";
import { Button } from "@/components/Button";
import { useStore, useWaku } from "@/hooks";
import { MessageContent } from "@/services/waku";
export const Waku: React.FunctionComponent<{}> = () => {
const { wakuStatus } = useStore();
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<p className="text-xs">(select credentials to initialize)</p>
</Subtitle>
<Status text="Waku status" mark={wakuStatus} />
<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.proofStatus}, {content.time})
</span>
:
</p>
<p>{content.text}</p>
</li>
);
}

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

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

17
src/constants.ts Normal file
View File

@ -0,0 +1,17 @@
import protobuf from "protobufjs";
export type ProtoChatMessageType = {
timestamp: number;
nick: string;
text: string;
};
export const ProtoChatMessage = new protobuf.Type("ChatMessage")
.add(new protobuf.Field("timestamp", 1, "uint64"))
.add(new protobuf.Field("nick", 2, "string"))
.add(new protobuf.Field("text", 3, "string"));
export const CONTENT_TOPIC = "/toy-chat/2/luzhou/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";

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

@ -0,0 +1,5 @@
export { useStore } from "./useStore";
export { useRLN } from "./useRLN";
export { useWallet } from "./useWallet";
export { useContract } from "./useContract";
export { useWaku } 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,
};
});

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

@ -0,0 +1,67 @@
import React from "react";
import { waku, Waku, WakuEventsNames, MessageContent } from "@/services/waku";
import { useStore } from "./useStore";
import { useRLN } from "./useRLN";
export const useWaku = () => {
const wakuRef = React.useRef<Waku>();
const [messages, setMessages] = React.useState<MessageContent[]>([]);
const { rln } = useRLN();
const { activeMembershipID, credentials, setWakuStatus } = useStore();
React.useEffect(() => {
if (!credentials || !activeMembershipID || !rln) {
return;
}
const statusListener = (event: CustomEvent) => {
setWakuStatus(event.detail || "");
};
waku.addEventListener(WakuEventsNames.Status, statusListener);
const messagesListener = (event: CustomEvent) => {
setMessages((prev) => [...prev, event.detail as MessageContent]);
};
waku.addEventListener(WakuEventsNames.Message, messagesListener);
let terminated = false;
const run = async () => {
if (terminated) {
return;
}
const options = {
rln,
credentials,
membershipID: activeMembershipID,
};
if (!wakuRef.current) {
await waku.init(options);
wakuRef.current = waku;
} else {
wakuRef.current.initEncoder(options);
}
};
run();
return () => {
terminated = true;
waku.removeEventListener(WakuEventsNames.Status, statusListener);
waku.removeEventListener(WakuEventsNames.Message, messagesListener);
};
}, [activeMembershipID, credentials, rln, setWakuStatus]);
const onSend = React.useCallback(
async (nick: string, text: string) => {
if (!wakuRef.current) {
return;
}
await wakuRef.current.sendMessage(nick, text);
},
[wakuRef]
);
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;
}

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

@ -0,0 +1,149 @@
import { ethers } from "ethers";
import {
create,
Keystore,
RLNDecoder,
RLNEncoder,
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();

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

@ -0,0 +1,202 @@
import {
createLightNode,
createEncoder,
createDecoder,
IDecodedMessage,
LightNode,
waitForRemotePeer,
} from "@waku/sdk";
import {
CONTENT_TOPIC,
ProtoChatMessage,
ProtoChatMessageType,
} from "@/constants";
import {
RLNDecoder,
RLNEncoder,
IdentityCredential,
RLNInstance,
RLNContract,
} from "@waku/rln";
import { RLN } from "@/services/rln";
type InitOptions = {
membershipID: number;
credentials: IdentityCredential;
rln: RLN;
};
export type MessageContent = {
nick: string;
text: string;
time: string;
proofStatus: string;
};
type SubscribeOptions = {
rlnContract: RLNContract;
node: LightNode;
decoder: RLNDecoder<IDecodedMessage>;
};
export enum WakuEventsNames {
Status = "status",
Message = "message",
}
export enum WakuStatusEventPayload {
INITIALIZING = "Initializing",
WAITING_FOR_PEERS = "Waiting for peers",
STARTING = "Starting the node",
READY = "Ready",
}
type EventListener = (event: CustomEvent) => void;
interface IWaku {
init: (options: InitOptions) => void;
initEncoder: (options: InitOptions) => void;
addEventListener: (name: WakuEventsNames, fn: EventListener) => void;
removeEventListener: (name: WakuEventsNames, fn: EventListener) => void;
}
export class Waku implements IWaku {
private contentTopic = CONTENT_TOPIC;
private readonly emitter = new EventTarget();
public node: undefined | LightNode;
private encoder: undefined | RLNEncoder;
private decoder: undefined | RLNDecoder<IDecodedMessage>;
private initialized = false;
private initializing = false;
constructor() {}
public async init(options: InitOptions) {
if (this.initialized || this.initializing || !options.rln.rlnInstance) {
return;
}
this.initializing = true;
this.initEncoder(options);
this.decoder = new RLNDecoder(
options.rln.rlnInstance,
createDecoder(this.contentTopic)
);
if (!this.node) {
this.emitStatusEvent(WakuStatusEventPayload.INITIALIZING);
this.node = await createLightNode({ defaultBootstrap: true });
this.emitStatusEvent(WakuStatusEventPayload.STARTING);
await this.node.start();
this.emitStatusEvent(WakuStatusEventPayload.WAITING_FOR_PEERS);
await waitForRemotePeer(this.node);
this.emitStatusEvent(WakuStatusEventPayload.READY);
if (options.rln.rlnContract) {
await this.subscribeToMessages({
node: this.node,
decoder: this.decoder,
rlnContract: options.rln.rlnContract,
});
}
}
this.initialized = true;
this.initializing = false;
}
public initEncoder(options: InitOptions) {
const { rln, membershipID, credentials } = options;
if (!rln.rlnInstance) {
return;
}
this.encoder = new RLNEncoder(
createEncoder({
ephemeral: false,
contentTopic: this.contentTopic,
}),
rln.rlnInstance,
membershipID,
credentials
);
}
public async sendMessage(nick: string, text: string): Promise<void> {
if (!this.node || !this.encoder) {
return;
}
const timestamp = new Date();
const msg = ProtoChatMessage.create({
text,
nick,
timestamp: Math.floor(timestamp.valueOf() / 1000),
});
const payload = ProtoChatMessage.encode(msg).finish();
console.log("Sending message with proof...");
await this.node.lightPush.send(this.encoder, { payload, timestamp });
console.log("Message sent!");
}
private async subscribeToMessages(options: SubscribeOptions) {
await options.node.filter.subscribe(options.decoder, (message) => {
try {
const { timestamp, nick, text } = ProtoChatMessage.decode(
message.payload
) as unknown as ProtoChatMessageType;
let proofStatus = "no proof";
if (message.rateLimitProof) {
console.log("Proof received: ", message.rateLimitProof);
try {
console.time("Proof verification took:");
const res = message.verify(options.rlnContract.roots());
console.timeEnd("Proof verification took:");
proofStatus = res ? "verified" : "not verified";
} catch (error) {
proofStatus = "invalid";
console.error("Failed to verify proof: ", error);
}
}
this.emitMessageEvent({
nick,
text,
proofStatus,
time: new Date(timestamp).toDateString(),
});
} catch (error) {
console.error("Failed in subscription listener: ", error);
}
});
}
public addEventListener(name: WakuEventsNames, fn: EventListener) {
return this.emitter.addEventListener(name, fn as any);
}
public removeEventListener(name: WakuEventsNames, fn: EventListener) {
return this.emitter.removeEventListener(name, fn as any);
}
private emitStatusEvent(payload: WakuStatusEventPayload) {
this.emitter.dispatchEvent(
new CustomEvent(WakuEventsNames.Status, { detail: payload })
);
}
private emitMessageEvent(payload: MessageContent) {
this.emitter.dispatchEvent(
new CustomEvent(WakuEventsNames.Message, { detail: payload })
);
}
}
export const waku = new Waku();

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;
};

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"]
}