feat: simplify rln-js (#297)

* remove old rln-js

* feat: simplify rln-js

* remove comment

* add example to CI
This commit is contained in:
Sasha 2024-01-24 20:51:13 +01:00 committed by GitHub
parent 504bcd4431
commit 698afe4dab
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
48 changed files with 6550 additions and 5993 deletions

View File

@ -20,7 +20,8 @@ jobs:
web-chat, web-chat,
noise-js, noise-js,
noise-rtc, noise-rtc,
relay-direct-rtc relay-direct-rtc,
rln-js
] ]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

12
ci/Jenkinsfile vendored
View File

@ -43,7 +43,7 @@ pipeline {
stage('noise-js') { steps { script { buildExample() } } } stage('noise-js') { steps { script { buildExample() } } }
stage('noise-rtc') { steps { script { buildExample() } } } stage('noise-rtc') { steps { script { buildExample() } } }
stage('relay-direct-rtc') { steps { script { buildExample() } } } stage('relay-direct-rtc') { steps { script { buildExample() } } }
stage('rln-js') { steps { script { buildNextJSExample() } } } stage('rln-js') { steps { script { buildExample() } } }
} }
} }
@ -86,13 +86,3 @@ def copyExample(example=STAGE_NAME) {
sh "mkdir -p ${dest}" sh "mkdir -p ${dest}"
sh "cp -r ${source}/. ${dest}" sh "cp -r ${source}/. ${dest}"
} }
def buildNextJSExample(example=STAGE_NAME) {
def dest = "${WORKSPACE}/build/docs/${example}"
dir("examples/${example}") {
sh 'npm install --silent'
sh 'npm run build'
sh "mkdir -p ${dest}"
sh "cp -r out/* ${dest}"
}
}

View File

@ -1,3 +0,0 @@
{
"extends": "../../.eslintrc.json"
}

View File

@ -1,35 +0,0 @@
# 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,30 +0,0 @@
# Using [RLN](https://rfc.vac.dev/spec/32/) in JavaScript
> Rate limiting nullifier (RLN) is a construct based on zero-knowledge proofs
> that provides an anonymous rate-limited signaling/messaging framework
> suitable for decentralized (and centralized) environments
**Demonstrates**:
- RLN:
- Generate credentials
- Insert membership to smart contract (Goerli testnet)
- Retrieve smart contract state
- Generate and send proofs
- Verify incoming proofs
- Keystore
- Next.js framework
# Getting Started
```shell
git clone https://github.com/waku-org/js-waku-examples
cd js-waku-examples/examples/rln-js
npm install
npm run dev
# open http://127.0.0.1:3000 In your browser
```
**There are a known issue using this webapp with Firefox + MetaMask. Try Chrome or Brave if you encounter any issue**.
The `master` branch's HEAD is deployed at https://examples.waku.org/rln-js/.

View File

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
examples/rln-js/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

173
examples/rln-js/index.html Normal file
View File

@ -0,0 +1,173 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title></title>
<link rel="apple-touch-icon" href="./favicon.png" />
<link rel="manifest" href="./manifest.json" />
<link rel="icon" href="./favicon.ico" />
<style>
* {
margin: 0;
padding: 0;
word-wrap: break-word;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
}
html {
font-size: 16px;
overflow: hidden;
}
body {
display: flex;
align-items: center;
padding: 10px;
flex-direction: column;
justify-content: center;
}
.container {
width: 100%;
min-width: 300px;
max-width: 800px;
height: 100%;
display: flex;
flex-direction: column;
align-content: space-between;
}
h2 {
text-align: center;
margin-bottom: 5px;
}
h3 {
margin-bottom: 10px;
}
h3:last-of-type {
margin-bottom: 20px;
}
h2 span,
h3 span {
font-weight: normal;
}
.progress {
color: #9ea13b;
}
.success {
color: #3ba183;
}
.error {
color: #c84740;
}
button.progress {
color: white;
background-color: #9ea13b;
}
button.success {
color: white;
background-color: #3ba183;
}
button.error {
color: white;
background-color: #c84740;
}
.pairingInfo {
display: flex;
flex-direction: column;
align-items: center;
}
.pairingInfo input {
display: block;
min-width: 250px;
width: 100%;
max-width: 600px;
font-size: 1.1rem;
line-height: 1.5rem;
padding: 5px;
margin-bottom: 10px;
}
.pairingInfo button {
flex-grow: 1;
cursor: pointer;
padding: 10px;
}
.pairingInfo button + button {
margin-left: 5px;
}
.chatArea {
}
.chatArea ul {
margin-bottom: 30px;
list-style: none;
}
.chatArea ul li + li {
margin-top: 5px;
}
.chatArea div {
display: flex;
flex-direction: column;
}
.chatArea div > * {
font-size: 1.1rem;
line-height: 1.5rem;
padding: 5px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="status">
<h3>
<b>Waku Status:</b>
<span id="status" class="progress">Starting...</span>
</h3>
</div>
<div class="chatArea" id="chat-area" style="display: none">
<h2>Chat</h2>
<ul id="messages"></ul>
<div>
<input id="nick" placeholder="Choose a nickname" type="text" />
<textarea
id="text"
placeholder="Type your message here"
type="text"
></textarea>
<button id="send" type="button">Send message</button>
</div>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>

View File

@ -0,0 +1,19 @@
{
"name": "Waku RLN",
"description": "Example showing Waku RLN capabilities.",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "favicon.png",
"type": "image/png",
"sizes": "192x192"
}
],
"display": "standalone",
"theme_color": "#ffffff",
"background_color": "#ffffff"
}

View File

@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,28 @@
{ {
"name": "rln-js", "name": "rln-chat",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "next build", "build": "webpack --config webpack.config.js",
"start": "npm run open && next dev", "start": "webpack-dev-server"
"lint": "next lint",
"open": "npx open-cli http://localhost:3000/rln-js"
}, },
"dependencies": { "dependencies": {
"@waku/rln": "0.1.1-0fbf6be", "@waku/rln": "0.1.1-0fbf6be",
"@waku/sdk": "^0.0.20", "@waku/sdk": "^0.0.22",
"@waku/utils": "^0.0.12", "@waku/utils": "^0.0.14",
"ethers": "^5.7.2", "ethers": "^5.7.2",
"multiaddr": "^10.0.1", "multiaddr": "^10.0.1",
"next": "13.5.6", "protobufjs": "^7.2.5"
"protobufjs": "^7.2.5",
"react": "^18",
"react-dom": "^18",
"zustand": "^4.4.4"
}, },
"devDependencies": { "devDependencies": {
"@metamask/types": "^1.1.0", "@metamask/types": "^1.1.0",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10",
"eslint": "^8", "eslint": "^8",
"eslint-config-next": "13.5.6", "eslint-config-next": "13.5.6",
"open-cli": "^7.2.0", "typescript": "^5",
"postcss": "^8", "copy-webpack-plugin": "^11.0.0",
"tailwindcss": "^3", "webpack": "^5.74.0",
"typescript": "^5" "webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
} }
} }

View File

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

View File

@ -1,27 +0,0 @@
@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

@ -1,28 +0,0 @@
import { Block, BlockTypes } from "@/components/Block";
import { Button } from "@/components/Button";
import { Subtitle } from "@/components/Subtitle";
import { useContract, useStore } from "@/hooks";
export const BlockchainInfo: 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

@ -1,17 +0,0 @@
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

@ -1,158 +0,0 @@
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

@ -1,45 +0,0 @@
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

@ -1,117 +0,0 @@
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>
);
}

View File

@ -1,18 +0,0 @@
"use client";
import { Header } from "./components/Header";
import { Waku } from "./components/Waku";
import { Keystore } from "./components/Keystore";
import { BlockchainInfo } from "./components/BlockchainInfo";
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 />
<BlockchainInfo />
<Keystore />
<KeystoreDetails />
<Waku />
</main>
);
}

View File

@ -1,22 +0,0 @@
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>
);
}

View File

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

View File

@ -1,23 +0,0 @@
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>
);
};

View File

@ -1,18 +0,0 @@
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>
);
};

View File

@ -1,13 +0,0 @@
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

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

View File

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

View File

@ -0,0 +1,153 @@
import protobuf from "protobufjs";
import { concat } from "@waku/utils/bytes";
import { IdentityCredential, Keystore } from "@waku/rln";
export const CONTENT_TOPIC = "/toy-chat/2/luzhou/proto";
export const CLUSTER_ID = 1;
export const MEMBERSHIP_ID = 14;
export const RLN_CREDENTIALS = IdentityCredential.fromBytes(
concat([
/* IDTrapdoor */ Keystore.fromArraylikeToBytes({
0: 182,
1: 79,
2: 126,
3: 47,
4: 227,
5: 67,
6: 22,
7: 100,
8: 128,
9: 168,
10: 33,
11: 164,
12: 240,
13: 233,
14: 91,
15: 245,
16: 75,
17: 156,
18: 224,
19: 189,
20: 174,
21: 19,
22: 104,
23: 69,
24: 190,
25: 34,
26: 222,
27: 244,
28: 119,
29: 236,
30: 43,
31: 29,
}),
/* IDNullifier */ Keystore.fromArraylikeToBytes({
0: 99,
1: 194,
2: 251,
3: 229,
4: 115,
5: 41,
6: 207,
7: 215,
8: 31,
9: 155,
10: 237,
11: 129,
12: 119,
13: 201,
14: 241,
15: 178,
16: 76,
17: 227,
18: 87,
19: 145,
20: 151,
21: 94,
22: 213,
23: 40,
24: 232,
25: 163,
26: 3,
27: 145,
28: 2,
29: 34,
30: 209,
31: 37,
}),
/* IDSecretHash */ Keystore.fromArraylikeToBytes({
0: 35,
1: 167,
2: 89,
3: 158,
4: 35,
5: 198,
6: 187,
7: 240,
8: 114,
9: 76,
10: 220,
11: 111,
12: 245,
13: 76,
14: 201,
15: 187,
16: 30,
17: 53,
18: 94,
19: 175,
20: 16,
21: 73,
22: 65,
23: 92,
24: 156,
25: 189,
26: 153,
27: 66,
28: 60,
29: 91,
30: 235,
31: 30,
}),
/* IDCommitment */ Keystore.fromArraylikeToBytes({
0: 181,
1: 107,
2: 5,
3: 148,
4: 160,
5: 49,
6: 176,
7: 143,
8: 203,
9: 53,
10: 127,
11: 44,
12: 190,
13: 133,
14: 75,
15: 42,
16: 96,
17: 153,
18: 78,
19: 63,
20: 205,
21: 66,
22: 9,
23: 72,
24: 127,
25: 210,
26: 22,
27: 133,
28: 37,
29: 28,
30: 91,
31: 4,
}),
])
);
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"));

View File

@ -1,30 +0,0 @@
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";
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",
}

View File

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

View File

@ -1,60 +0,0 @@
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,
};
};

View File

@ -1,83 +0,0 @@
import React from "react";
import { useStore } from "./useStore";
import { useRLN } from "./useRLN";
import { SEPOLIA_CONTRACT } from "@waku/rln";
import { StatusEventPayload } from "@/constants";
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,
};
};

View File

@ -1,50 +0,0 @@
"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,
};
};

View File

@ -1,68 +0,0 @@
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,
};
});

View File

@ -1,67 +0,0 @@
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 };
};

View File

@ -1,62 +0,0 @@
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);
}

View File

@ -0,0 +1,19 @@
import { initUI } from "./ui";
import { initRLN } from "./rln";
import { initWaku } from "./waku";
async function run() {
const { onLoaded, onStatusChange, registerEvents } = initUI();
const { encoder, decoder, rlnContract } = await initRLN(onStatusChange);
const { onSend, onSubscribe } = await initWaku({
encoder,
decoder,
rlnContract,
onStatusChange,
});
onLoaded();
registerEvents({ onSend, onSubscribe });
}
run();

View File

@ -1,14 +0,0 @@
/// <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;
}

View File

@ -0,0 +1,61 @@
import { ethers } from "ethers";
import {
create,
RLNEncoder,
RLNDecoder,
RLNContract,
SEPOLIA_CONTRACT,
} from "@waku/rln";
import { createEncoder, createDecoder } from "@waku/sdk";
import { CONTENT_TOPIC, MEMBERSHIP_ID, RLN_CREDENTIALS } from "./const";
export async function initRLN(onStatusChange) {
onStatusChange("Connecting to wallet...");
const ethereum = window.ethereum;
if (!ethereum) {
const err =
"Missing or invalid Ethereum provider. Please install MetaMask.";
onStatusChange(err, "error");
throw Error(err);
}
try {
await ethereum.request({ method: "eth_requestAccounts" });
} catch (err) {
onStatusChange("Failed to access MetaMask", "error");
throw Error(err);
}
const provider = new ethers.providers.Web3Provider(ethereum, "any");
onStatusChange("Initializing RLN...");
let rlnInstance, rlnContract;
try {
rlnInstance = await create();
rlnContract = await RLNContract.init(rlnInstance, {
registryAddress: SEPOLIA_CONTRACT.address,
provider: provider.getSigner(),
});
} catch (err) {
onStatusChange("Failed to initialize RLN", "error");
throw Error(err);
}
const encoder = new RLNEncoder(
createEncoder({
ephemeral: false,
contentTopic: CONTENT_TOPIC,
}),
rlnInstance,
MEMBERSHIP_ID,
RLN_CREDENTIALS
);
const decoder = new RLNDecoder(rlnInstance, createDecoder(CONTENT_TOPIC));
onStatusChange("RLN initialized", "success");
return {
encoder,
decoder,
rlnContract,
};
}

View File

@ -1,135 +0,0 @@
import { ethers } from "ethers";
import {
create,
Keystore,
RLNContract,
SEPOLIA_CONTRACT,
RLNInstance,
} from "@waku/rln";
import { isBrowserProviderValid } from "@/utils/ethereum";
import { StatusEventPayload } from "@/constants";
export enum RLNEventsNames {
Status = "status",
Keystore = "keystore-changed",
}
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();

View File

@ -1,202 +0,0 @@
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();

53
examples/rln-js/src/ui.js Normal file
View File

@ -0,0 +1,53 @@
const status = document.getElementById("status");
const chat = document.getElementById("chat-area");
const messages = document.getElementById("messages");
const nickInput = document.getElementById("nick");
const textInput = document.getElementById("text");
const sendButton = document.getElementById("send");
export const initUI = () => {
const onStatusChange = (newStatus, className) => {
status.innerText = newStatus;
status.className = className || "progress";
};
const onLoaded = () => {
chat.style.display = "block";
};
const _renderMessage = (nick, text, time, validation) => {
messages.innerHTML += `
<li>
(${nick})(${validation})
<strong>${text}</strong>
<i>[${new Date(time).toISOString()}]</i>
</li>
`;
};
const registerEvents = (events) => {
events.onSubscribe((nick, text, time, validation) => {
_renderMessage(nick, text, time, validation);
});
sendButton.addEventListener("click", async () => {
const nick = nickInput.value;
const text = textInput.value;
if (!nick || !text) {
console.log("Not sending message: missing nick or text.");
return;
}
await events.onSend(nick, text);
textInput.value = "";
});
};
return {
onLoaded,
registerEvents,
onStatusChange,
};
};

View File

@ -1,17 +0,0 @@
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;
};

View File

@ -0,0 +1,76 @@
import { createLightNode, waitForRemotePeer } from "@waku/sdk";
import { ProtoChatMessage } from "./const";
export async function initWaku({
encoder,
decoder,
rlnContract,
onStatusChange,
}) {
onStatusChange("Initializing Waku...");
const node = await createLightNode({
defaultBootstrap: true,
});
onStatusChange("Waiting for peers");
await node.start();
await waitForRemotePeer(node);
const onSend = async (nick, text) => {
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...");
const res = await node.lightPush.send(encoder, { payload, timestamp });
console.log("Message sent:", res);
};
onStatusChange("Subscribing to content topic...");
const subscription = await node.filter.createSubscription();
const onSubscribe = async (cb) => {
await subscription.subscribe(decoder, (message) => {
try {
const { timestamp, nick, text } = ProtoChatMessage.decode(
message.payload
);
let proofStatus = "no proof";
if (message.rateLimitProof) {
console.log("Proof received: ", message.rateLimitProof);
try {
console.time("Proof verification took:");
const res = message.verify(rlnContract.roots());
console.timeEnd("Proof verification took:");
proofStatus = res ? "verified" : "not verified";
} catch (error) {
proofStatus = "invalid";
console.error("Failed to verify proof: ", error);
}
}
console.log({
nick,
text,
proofStatus,
time: new Date(timestamp).toDateString(),
});
cb(nick, text, timestamp, proofStatus);
} catch (error) {
console.error("Failed in subscription listener: ", error);
}
});
};
onStatusChange("Waku initialized", "success");
return {
onSend,
onSubscribe,
};
}

View File

@ -1,20 +0,0 @@
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;

View File

@ -1,27 +0,0 @@
{
"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"]
}

View File

@ -0,0 +1,19 @@
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "build"),
filename: "./index.js",
},
experiments: {
asyncWebAssembly: true,
},
mode: "development",
plugins: [
new CopyWebpackPlugin({
patterns: ["index.html", "favicon.ico", "favicon.png", "manifest.json"],
}),
],
};