Use ferry chat to replace current code. (#28)

This commit is contained in:
kaichao 2024-05-21 15:30:56 +08:00 committed by GitHub
parent c48cc59ccd
commit a2b77b369d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
57 changed files with 3768 additions and 11192 deletions

21
.eslintrc.cjs Normal file
View File

@ -0,0 +1,21 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "warn",
"prefer-const": "off",
},
}

49
.gitignore vendored
View File

@ -1,35 +1,24 @@
# 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
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# local env files
.env*.local
node_modules
dist
dist-ssr
*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -1,35 +1,63 @@
# waku-frontend
Waku's frontend. Interact with your waku node via this simple user interface
# Waku Frontend
## Getting Started
The chat application to use The Waku Network.
First, run the development server:
## Why
- a PoC to battle test The Waku Network.
- create user experience with REST API / WebSocket
- facilitate the developer adoption of Waku protocols
- split concern to harden the protocol stabliity with C/S model
- incubate app based sync protocol
*Notes:* This project is still in the early stage of development, and the data is not persistent, you may lose the message history any time.
## Features
### Public community chat
The public chat room is open to everyone who knows the community name. The content is not encrypted.
## Plans
- WebSocket to support real-time chat
- End-to-end encryption for 1to1 chat
## Development
```shell
npm install
```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.
## Caddy configuration
## To run independently
```
your-domain.com {
@cors_preflight {
method OPTIONS
}
respond @cors_preflight 204
```bash
npm run build
npm run serve
header {
Access-Control-Allow-Origin *
Access-Control-Allow-Methods GET,POST,OPTIONS,HEAD,PATCH,PUT,DELETE
Access-Control-Allow-Headers User-Agent,Content-Type,X-Api-Key
Access-Control-Max-Age 86400
}
reverse_proxy :8645
}
```
## To run in docker
## Depend APIs
```bash
npm run build
docker build -t waku_frontend .
docker run -d -p 8080:80 waku_frontend
```
- /relay/v1/auto/messages
- /store/v1/messages
Open [http://localhost:8080](http://localhost:8080) with your browser to see the result.
## Known Issues
- https://github.com/waku-org/nwaku/issues/2615, temporary fix is set pageSize to `300`.

17
components.json Normal file
View File

@ -0,0 +1,17 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/globals.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
}
}

11
docs/features.md Normal file
View File

@ -0,0 +1,11 @@
Basic flow:
- alice create a community by generate a chat keypair, content topic is the hash of the public key
- alice share the private key with bob
- bob derive the content topic from private key and subscribe to the topic as a member of the community
- alice encrypt the message with the public key and send to the topic
- bob get the message and decrypt with the private key
Admin flow:
- alice create a community by generate an admin keypair, content topic is the hash of the public chat key
- alice send specific messages to the topic, bob don't have the key, so he can't send it.
- todo...

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/logo-waku.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Waku Chat</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

12071
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,44 @@
{
"name": "rln-js",
"version": "0.1.0",
"name": "waku-frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"serve": "serve ./out",
"lint": "next lint"
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@waku/rln": "0.1.1-60a5070",
"@waku/utils": "^0.0.12",
"ethers": "^5.7.2",
"next": "13.5.6",
"react": "^18",
"react-dom": "^18",
"zustand": "^4.4.4"
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-slot": "^1.0.2",
"axios": "^1.6.8",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"lucide-react": "^0.368.0",
"next-themes": "^0.3.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sonner": "^1.4.41",
"tailwind-merge": "^2.2.2",
"tailwindcss-animate": "^1.0.7"
},
"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"
"@types/node": "^20.12.7",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.19",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.3",
"typescript": "^5.2.2",
"vite": "^5.2.0"
}
}

View File

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

10
public/logo-waku.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

View File

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

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

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

Before

Width:  |  Height:  |  Size: 629 B

487
src/App.tsx Normal file
View File

@ -0,0 +1,487 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
import axios from "axios";
import { Github, Settings, X } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import logo from "./assets/logo-waku.svg";
interface Message {
payload: string;
contentTopic: string;
timestamp: number;
}
interface Cursor {
digest: {
data: string;
};
sender_time: number;
store_time: number;
pubsub_topic: string;
}
interface ResponseData {
messages: Message[];
cursor?: Cursor;
}
interface CommunityMetadata {
name: string;
contentTopic: string;
}
const SERVICE_ENDPOINT = "https://waku.whisperd.tech";
const COMMUNITY_CONTENT_TOPIC_PREFIX = "/universal/1/community";
function App() {
const [newMessage, setNewMessage] = useState("");
const [username, setUsername] = useState("");
const [usernameInput, setUsernameInput] = useState("");
const [messages, setMessages] = useState<Message[]>([]);
const [community, setCommunity] = useState<CommunityMetadata | undefined>(
undefined
);
const [joinedCommunities, setJoinedCommunities] = useState<
CommunityMetadata[]
>([]);
const [communityName, setCommunityName] = useState("");
const [apiEndpoint, setApiEndpoint] = useState(SERVICE_ENDPOINT);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateMessage = (e: any) => setNewMessage(e.target.value);
useEffect(() => {
const name = GetUser();
setUsername(name);
const endpoint = localStorage.getItem("apiEndpoint");
if (endpoint) {
setApiEndpoint(endpoint);
}
const localCommunity = localStorage.getItem("community");
console.log("current community", localCommunity);
setCommunity(localCommunity ? JSON.parse(localCommunity) : undefined);
const communities = localStorage.getItem("communities");
if (communities) {
const parsed = JSON.parse(communities);
setJoinedCommunities(parsed);
console.log("joined communities", parsed);
}
}, []);
useEffect(() => {
const fetchAllMessages = async () => {
try {
const joinedContentTopics = joinedCommunities
.map(
(c: CommunityMetadata) =>
`${COMMUNITY_CONTENT_TOPIC_PREFIX}/${c.contentTopic}`
)
.join(",");
if (joinedContentTopics === "") {
return;
}
let url = `${apiEndpoint}/store/v1/messages?contentTopics=${joinedContentTopics}&ascending=false&pageSize=300`;
const response = await axios.get(url);
console.log("Data:", response.data);
setMessages((prev) => {
const filtered = response.data.messages.filter((msg: Message) => {
const found = prev.find(
(item) =>
item.payload === msg.payload &&
item.timestamp === msg.timestamp &&
item.contentTopic === msg.contentTopic
);
return !found;
});
const result = [...prev, ...filtered].sort(
(a: Message, b: Message) => b.timestamp - a.timestamp
);
return result;
});
handleCursor(url, response.data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
const handleCursor = async (baseUrl: string, data: ResponseData) => {
if (data.cursor) {
const url = `${baseUrl}&pubsubTopic=${data.cursor.pubsub_topic}&digest=${data.cursor.digest.data}&senderTime=${data.cursor.sender_time}&storeTime=${data.cursor.store_time}`;
const response = await axios.get(url);
setMessages((prev) => {
const filtered = response.data.messages.filter((msg: Message) => {
const found = prev.find(
(item) =>
item.payload === msg.payload &&
item.timestamp === msg.timestamp &&
item.contentTopic === msg.contentTopic
);
return !found;
});
const result = [...prev, ...filtered].sort(
(a: Message, b: Message) => b.timestamp - a.timestamp
);
return result;
});
handleCursor(baseUrl, response.data);
}
};
const intervalId = setInterval(fetchAllMessages, 5000); // Trigger fetchData every 5 seconds
return () => clearInterval(intervalId);
}, [joinedCommunities, apiEndpoint]);
const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
const CreateUser = async (name: string) => {
console.log("creating user");
localStorage.setItem("username", name);
return name;
};
const GetUser = () => {
const name = localStorage.getItem("username");
return name || "";
};
const Send = async (content: string) => {
console.log("sending message", content);
const payload = {
content: content,
name: username,
timestamp: Math.floor(Date.now() / 1000),
};
const bytes = btoa(JSON.stringify(payload));
const message = {
payload: bytes,
contentTopic: `${COMMUNITY_CONTENT_TOPIC_PREFIX}/${
community!.contentTopic
}`,
};
const response = await axios.post(
`${apiEndpoint}/relay/v1/auto/messages`,
JSON.stringify(message),
{
headers: {
"Content-Type": "application/json",
},
}
);
return response.data;
};
const sendMessage = async () => {
if (!username || !newMessage) {
toast.warning("Username or message is empty.");
return;
}
try {
let result = await Send(newMessage);
console.log("result", result);
setNewMessage("");
} catch (err) {
toast.error(`Error happens: ${err}`);
}
};
const createUser = async () => {
try {
const name = await CreateUser(usernameInput);
setUsername(name);
toast("User has been created.");
} catch (err) {
toast.error(`Error happens: ${err}`);
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateCommunityName = (e: any) => setCommunityName(e.target.value);
const createCommunity = (name: string) => {
const metadata: CommunityMetadata = {
name: name,
contentTopic: name,
};
const communities = localStorage.getItem("communities");
if (communities) {
const parsed = JSON.parse(communities);
if (parsed.find((item: CommunityMetadata) => item.name === name)) {
toast.warning("Community already exists.");
return;
}
parsed.push(metadata);
localStorage.setItem("communities", JSON.stringify(parsed));
setJoinedCommunities(parsed);
} else {
localStorage.setItem("communities", JSON.stringify([metadata]));
setJoinedCommunities([metadata]);
}
setCommunity(metadata);
localStorage.setItem("community", JSON.stringify(metadata));
setCommunityName("");
return metadata;
};
const deleteCommunity = (index: number) => () => {
const communities = localStorage.getItem("communities");
if (communities) {
const parsed = JSON.parse(communities);
parsed.splice(index, 1);
localStorage.setItem("communities", JSON.stringify(parsed));
setJoinedCommunities(parsed);
console.log("delete community", parsed);
setCommunity(undefined);
localStorage.removeItem("community");
}
};
const selectCommunity = (index: number) => {
console.log("select community", joinedCommunities[index]);
setCommunity(joinedCommunities[index]);
localStorage.setItem("community", JSON.stringify(joinedCommunities[index]));
};
const saveSettings = () => {
localStorage.setItem("apiEndpoint", apiEndpoint);
};
const decodeMsg = (index: number, msg: Message) => {
try {
if (
msg.contentTopic !==
`${COMMUNITY_CONTENT_TOPIC_PREFIX}/${community?.contentTopic}`
) {
return;
}
const formtMsg = JSON.parse(atob(msg.payload));
return (
<li key={index} className="mb-1">
<div className="flex flex-row justify-between gap-2">
<Label>
<span
className={
formtMsg.name == username ? "bg-green-200" : "bg-gray-300"
}
>
{formtMsg.name}:
</span>{" "}
{formtMsg.content}
</Label>
<Label>{formatDate(formtMsg.timestamp)}</Label>
</div>
</li>
);
} catch (err) {
console.log("decode message error", msg, err);
}
};
const settingsDialog = () => {
return (
<Dialog>
<DialogTrigger asChild>
<Settings />
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Settings</DialogTitle>
<DialogDescription>
Make changes to your settings here. Click save when you're done.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="name" className="text-right">
REST API
</Label>
<Input
id="name"
onChange={(e) => setApiEndpoint(e.target.value)}
autoComplete="off"
autoCorrect="off"
defaultValue={apiEndpoint}
className="col-span-3"
/>
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="submit" onClick={saveSettings}>
Save
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
const logoImage = () => {
return (
<img
height={100}
width={100}
src={logo}
alt="logo"
className="rounded-2xl"
/>
);
};
const createCommunityDialog = () => {
return (
<div className="flex flex-col items-center gap-3">
<Input
className="w-[200px]"
value={communityName}
onChange={updateCommunityName}
placeholder="Input the community name"
autoComplete="off"
autoCorrect="off"
/>
<Label className="text-gray-500">
For example: <span className="underline">waku</span>
</Label>
<Button className="w-50" onClick={() => createCommunity(communityName)}>
Join Community
</Button>
</div>
);
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
return date.toLocaleString();
};
return (
<div>
<div className="absolute right-36 top-16">
<Label className="text-md">Hello, {username}</Label>
</div>
<div className="absolute right-24 top-16">
<a href="https://github.com/waku-org/waku-frontend" target="_blank">
<Github />
</a>
</div>
<div className="absolute right-16 top-16">{settingsDialog()}</div>
{!username && (
<div className="flex flex-col gap-5 items-center justify-center h-screen mt-[-60px]">
{logoImage()}
<div className="flex flex-col items-center gap-3">
<Input
value={usernameInput}
onChange={(e) => setUsernameInput(e.target.value)}
placeholder="Enter your username"
autoComplete="off"
autoCorrect="off"
/>
<Button className="w-32" onClick={createUser}>
Create
</Button>
</div>
</div>
)}
{username && joinedCommunities.length == 0 && (
<div className="flex flex-col gap-5 items-center justify-center h-screen mt-[-60px]">
{logoImage()}
{createCommunityDialog()}
</div>
)}
{username && joinedCommunities.length > 0 && (
<div className="flex md:flex-row flex-col h-screen items-center justify-center gap-10">
<div className="flex flex-col gap-8 mt-36 md:mt-0">
<div>
<h1 className="text-xl font-bold mb-2">Communities</h1>
<ul>
{joinedCommunities.map((item, index) => (
<li key={index} onClick={() => selectCommunity(index)}>
<div className="flex flex-row items-center gap-1">
<Label
className={
item.name == community?.name ? "bg-green-200" : ""
}
>
{item.name}
</Label>
<X size={18} onClick={deleteCommunity(index)} />
</div>
</li>
))}
</ul>
</div>
{createCommunityDialog()}
</div>
<div className="flex flex-col gap-10 items-center justify-center">
{logoImage()}
{community && (
<div className="flex flex-col gap-10 items-center">
<div className="flex w-full max-w-sm items-center space-x-2">
<Input
value={newMessage}
onChange={updateMessage}
placeholder="Input your message"
autoComplete="off"
autoCorrect="off"
/>
<Button className="w-32" onClick={sendMessage}>
Send
</Button>
</div>
<div>
<h1 className="text-xl font-bold mb-2">Message History</h1>
<ScrollArea className="h-[300px] md:w-[650px] rounded-md border p-4 bg-gray-100">
<ul className="text-sm flex flex-col gap-1">
{messages.map((msg, index) => decodeMsg(index, msg))}
</ul>
</ScrollArea>
</div>
</div>
)}
</div>
</div>
)}
</div>
);
}
export default App;

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

@ -1,24 +0,0 @@
import { Block, BlockTypes } from "@/components/Block";
import { Title } from "@/components/Title";
import { Button } from "@/components/Button";
type HeaderProps = {
children?: React.ReactNode;
onWalletConnect?: () => void;
}
export const Header: React.FunctionComponent<HeaderProps> = (props) => {
return (
<>
<Block className="mb-5" type={BlockTypes.FlexHorizontal}>
<Title>Waku</Title>
{props.onWalletConnect && (
<Button onClick={props.onWalletConnect}>
Connect Wallet
</Button>
)}
</Block>
{props.children}
</>
);
};

View File

@ -1,155 +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 } from "@/hooks";
import { useKeystore } from "@/hooks/useKeystore";
export const Keystore: React.FunctionComponent<{}> = () => {
const { wallet, keystoreCredentials } = useStore();
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 and register on chain</p>
<Button
disabled={!wallet || !password}
onClick={() => onRegisterCredentials(password)}
className={wallet && password ? "" : "cursor-not-allowed"}
>
Register new 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,12 +0,0 @@
import Link from "next/link";
import { Block } from "@/components/Block";
export const Menu: React.FunctionComponent<{}> = () => {
return (
<Block className="m-5 flex text-lg">
<p className="mr-5">{">"}</p>
<p className="mr-5"><Link href="/">Chat</Link></p>
<p><Link href="/keystore">Keystore</Link></p>
</Block>
);
};

View File

@ -1,192 +0,0 @@
import React from "react";
import { Block } from "@/components/Block";
import { Subtitle } from "@/components/Subtitle";
import { Button } from "@/components/Button";
import { MessageContent } from "@/hooks";
import { SUPPORTED_PUBSUB_TOPICS } from "@/constants";
type WakuProps = {
onSend: (nick: string, text: string) => Promise<void>;
activeContentTopic: string;
activePubsubTopic: string;
messages: MessageContent[];
onActiveContentTopicChange: (contentTopic: string) => void;
onActivePubsubTopicChange: (pubsubTopic: string) => void;
}
export const Waku: React.FunctionComponent<WakuProps> = (props) => {
const {
nick,
text,
onNickChange,
onMessageChange,
resetText,
} = useMessage();
const [
contentTopic,
onContentTopicChange,
] = useTopic<HTMLInputElement>(props.activeContentTopic);
const [
pubsubTopic,
onPubsubTopicChange,
] = useTopic<HTMLSelectElement>(props.activePubsubTopic);
const onSendClick = async () => {
await props.onSend(nick, text);
resetText();
};
const renderedMessages = React.useMemo(
() => props.messages.map(renderMessage),
[props.messages]
);
return (
<Block className="mt-10 flex flex-col md:flex-row lg:flex-row">
<Block>
<Block>
<Subtitle>Chat</Subtitle>
</Block>
<Block className="mt-5">
<label
htmlFor="pubsubTopic"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Pubsub topic
</label>
<select
id="pubsubTopic"
value={pubsubTopic}
onChange={onPubsubTopicChange}
className="w-96 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 pr-4 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"
>
{SUPPORTED_PUBSUB_TOPICS.map((v) => (
<option key={v} value={v}>{v}</option>
))}
</select>
<Button className="mt-1" onClick={() => { props.onActivePubsubTopicChange(pubsubTopic); }}>Change</Button>
</Block>
<Block className="mt-5">
<label
htmlFor="contentTopic"
className="block text-sm mb-2 font-medium text-gray-900 dark:text-white"
>
Content topic
</label>
<input
type="text"
id="contentTopic"
value={contentTopic}
onChange={onContentTopicChange}
className="w-96 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"
/>
<Button className="mt-1" onClick={() => { props.onActiveContentTopicChange(contentTopic); }}>Change</Button>
</Block>
<Block className="mt-4 mr-10 min-w-fit">
<label
htmlFor="nick"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Your nickname
</label>
<input
type="text"
id="nick"
placeholder="Choose a nickname"
value={nick}
onChange={onNickChange}
className="w-96 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-5">
<Block className="mb-2">
<label
htmlFor="message"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Message
</label>
<textarea
id="message"
value={text}
onChange={onMessageChange}
placeholder="Text your message here"
className="w-96 h-60 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>
<Block className="max-w-screen-md mt-10 md:mt-0">
<p className="text-l mb-4">Messages</p>
<div>
<ul>{renderedMessages}</ul>
</div>
</Block>
</Block>
);
};
function useTopic<T>(globalTopic: string): [string, (e: React.SyntheticEvent<T>) => void] {
const [topic, setTopic] = React.useState<string>(globalTopic);
React.useEffect(() => {
setTopic(globalTopic);
}, [globalTopic]);
const onTopicChange = (e: React.SyntheticEvent<T>) => {
const target = e.currentTarget as any;
setTopic(target?.value || "");
};
return [
topic,
onTopicChange,
];
}
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<HTMLTextAreaElement>) => {
setText(e.currentTarget.value || "");
};
const resetText = () => {
setText("");
};
return {
nick,
text,
resetText,
onNickChange,
onMessageChange,
};
}
function renderMessage(content: MessageContent) {
return (
<li key={`${content.nick}-${content.timestamp}-${content.text}`} className="mb-4">
<p>
<span className="text-lg">{content.nick}</span>
<span className="text-sm font-bold">
({(new Date(content.timestamp)).toDateString()})
</span>
:
</p>
<p className="break-words">{content.text}</p>
</li>
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

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,32 +0,0 @@
"use client";
import { Header } from "@/app/components/Header";
import { Keystore } from "@/app/components/Keystore";
import { KeystoreDetails } from "@/app/components/KeystoreDetails";
import { useWallet } from "@/hooks";
import { Status } from "@/components/Status";
import { useStore } from "@/hooks";
export default function KeystorePage() {
const { onWalletConnect } = useWallet();
const { appStatus, wallet } = useStore();
if (typeof window !== "undefined" && !window?.ethereum) {
return (
<main className="flex min-h-screen flex-col p-6 font-mono max-w-screen-lg">
<Header />
<p className="text-xl">Seems you do not have MetaMask installed. Please, install and reload the page.</p>
</main>
);
}
return (
<main className="flex min-h-screen flex-col p-6 font-mono max-w-screen-lg">
<Header onWalletConnect={onWalletConnect}>
<Status text="Application status" mark={appStatus} />
{ wallet && <p className="mt-3 text-sm">Wallet connected: {wallet}</p> }
</Header>
<Keystore />
<KeystoreDetails />
</main>
);
}

View File

@ -1,26 +0,0 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { Menu } from "@/app/components/Menu";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "nwaku front-end",
description: "Send messages through you local node, register to RLN, read and export Keystore",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<Menu />
{children}
</body>
</html>
);
}

View File

@ -1,62 +0,0 @@
"use client";
import { Header } from "@/app/components/Header";
import { Waku } from "@/app/components/Waku";
import { useWaku } from "@/hooks";
import { DebugInfo } from "@/services/waku";
export default function Home() {
const {
onSend,
messages,
debugInfo,
contentTopic,
onContentTopicChange,
pubsubTopic,
onPubsubTopicChange
} = useWaku();
return (
<main className="flex min-h-screen flex-col p-6 font-mono max-w-screen-lg">
<Header>
<DebugInfo value={debugInfo} />
</Header>
<Waku
onSend={onSend}
messages={messages}
activeContentTopic={contentTopic}
onActiveContentTopicChange={onContentTopicChange}
activePubsubTopic={pubsubTopic}
onActivePubsubTopicChange={onPubsubTopicChange}
/>
</main>
);
}
type DebugInfoProps = {
value?: DebugInfo;
}
const DebugInfo: React.FunctionComponent<DebugInfoProps> = (props) => {
if (!props.value) {
return;
}
return (
<details className="border rounded p-2">
<summary className="cursor-pointer bg-gray-300 p-2 rounded-md">
<span className="font-bold">Show node info</span>
</summary>
<div className="mt-2 text-sm break-words">
<p className="mb-2">Health: {props.value.health}</p>
<p className="mb-2">Version: {props.value.version}</p>
<p className="mb-2">ENR URI: {props.value.enrUri}</p>
<p className="mb-2">Listen Addresses:</p>
<ul>
{props.value.listenAddresses.map((address, index) => (
<li key={index}>{address}</li>
))}
</ul>
</div>
</details>
);
}

10
src/assets/logo-waku.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

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,20 +0,0 @@
type ButtonProps = {
children: any;
className?: string;
disabled?: boolean;
onClick?: (e?: any) => void;
};
export const Button: React.FunctionComponent<ButtonProps> = (props) => {
return (
<button
disabled={props.disabled}
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,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@ -0,0 +1,120 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

View File

@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@ -0,0 +1,46 @@
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

View File

@ -0,0 +1,29 @@
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

View File

@ -1,15 +0,0 @@
export const CONTENT_TOPIC = "/toy-chat/2/luzhou/proto";
export const PUBSUB_TOPIC = "/waku/2/rs/1/0";
export const SUPPORTED_PUBSUB_TOPICS = [
"/waku/2/rs/1/0",
"/waku/2/rs/1/1",
"/waku/2/rs/1/2",
"/waku/2/rs/1/3",
"/waku/2/rs/1/4",
"/waku/2/rs/1/5",
"/waku/2/rs/1/6",
"/waku/2/rs/1/7",
];
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";

76
src/globals.css Normal file
View File

@ -0,0 +1,76 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

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

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 || !rln?.ethProvider) {
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,113 +0,0 @@
import React from "react";
import { useStore } from "./useStore";
import { useRLN } from "./useRLN";
import { SEPOLIA_CONTRACT } from "@waku/rln";
import { StatusEventPayload } from "@/services/rln";
import { SIGNATURE_MESSAGE } from "@/constants";
type UseKeystoreResult = {
onReadCredentials: (hash: string, password: string) => void;
onRegisterCredentials: (password: string) => void;
};
export const useKeystore = (): UseKeystoreResult => {
const { rln } = useRLN();
const {
setActiveCredential,
setActiveMembershipID,
setAppStatus,
setCredentials,
} = useStore();
const generateCredentials = 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
);
return credentials;
};
const onRegisterCredentials = React.useCallback(
async (password: string) => {
if (!rln?.rlnContract || !password) {
console.log(`Not registering - missing dependencies: contract-${!!rln?.rlnContract}, password-${!!password}`);
return;
}
try {
const credentials = await generateCredentials();
if (!credentials) {
console.log("No credentials registered.");
return;
}
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);
setCredentials(credentials);
setActiveMembershipID(membershipID);
rln.saveKeystore();
setAppStatus(StatusEventPayload.CREDENTIALS_REGISTERED);
} catch (error) {
setAppStatus(StatusEventPayload.CREDENTIALS_FAILURE);
console.error("Failed to register to RLN Contract: ", error);
return;
}
},
[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,
};
};
function randomNumber(): number {
return Math.ceil(Math.random() * 1000);
}

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,74 +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;
wallet: string;
setWallet: (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 })),
wallet: "",
setWallet: (v: string) => set((state) => ({ ...state, wallet: 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,115 +0,0 @@
import React from "react";
import { CONTENT_TOPIC, PUBSUB_TOPIC } from "@/constants";
import { DebugInfo, Message, waku } from "@/services/waku";
export type MessageContent = {
nick: string;
text: string;
timestamp: number;
};
export const useWaku = () => {
const [contentTopic, setContentTopic] = React.useState<string>(CONTENT_TOPIC);
const [pubsubTopic, setPubsubTopic] = React.useState<string>(PUBSUB_TOPIC);
const [messages, setMessages] = React.useState<Map<string, MessageContent>>(new Map());
const [debugInfo, setDebugInfo] = React.useState<undefined | DebugInfo>();
React.useEffect(() => {
const messageListener = (event: CustomEvent) => {
const nextMessages = new Map(messages);
const newMessages: Message[] = event.detail;
newMessages.forEach((m) => {
try {
const payload = JSON.parse(atob(m.payload));
const message: MessageContent = {
nick: payload?.nick || "unknown",
text: payload?.text || "empty",
timestamp: m.timestamp || Date.now(),
};
nextMessages.set(`${message.nick}-${message.timestamp}-${message.text}`, message);
} catch(error) {
console.error("Failed to parse message:", error);
}
});
setMessages(nextMessages);
};
waku.relay.addEventListener(contentTopic, messageListener);
return () => {
waku.relay.removeEventListener(contentTopic, messageListener);
};
}, [messages, setMessages, contentTopic]);
React.useEffect(() => {
const debugInfoListener = (event: CustomEvent) => {
const debugInfo = event.detail;
if (!debugInfo) {
return;
}
setDebugInfo(debugInfo);
};
waku.debug.addEventListener("debug", debugInfoListener);
return () => {
waku.debug.removeEventListener("debug", debugInfoListener);
};
}, [debugInfo, setDebugInfo]);
const onSend =
async (nick: string, text: string) => {
const timestamp = Date.now();
await waku.relay.send(pubsubTopic, {
version: 0,
timestamp,
contentTopic,
payload: btoa(JSON.stringify({
nick,
text
})),
});
const id = `${nick}-${timestamp}-${text}`;
setMessages((prev) => {
if (prev.has(id)) {
return prev;
}
const next = new Map(prev);
next.set(id, { nick, timestamp, text });
return next;
});
};
const onContentTopicChange = async (nextContentTopic: string) => {
if (nextContentTopic === contentTopic) {
return;
}
setContentTopic(nextContentTopic);
};
const onPubsubTopicChange = async (nextPubsubTopic: string) => {
if (nextPubsubTopic === pubsubTopic) {
return;
}
setPubsubTopic(nextPubsubTopic);
waku.relay.changeActivePubsubTopic(nextPubsubTopic);
};
return {
onSend,
debugInfo,
contentTopic,
onContentTopicChange,
pubsubTopic,
onPubsubTopicChange,
messages: Array.from(messages.values()),
};
};

View File

@ -1,63 +0,0 @@
import React from "react";
import { useStore } from "./useStore";
import { isEthereumEvenEmitterValid } from "@/utils/ethereum";
import { useRLN } from "./useRLN";
type UseWalletResult = {
onWalletConnect: () => void;
};
export const useWallet = (): UseWalletResult => {
const { rln } = useRLN();
const { setEthAccount, setChainID, setWallet } = 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 onWalletConnect = async () => {
const ethereum = window.ethereum;
if (!ethereum) {
console.log("No ethereum instance found.");
return;
}
if (!rln?.rlnInstance) {
console.log("RLN instance is not initialized.");
return;
}
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) as unknown as string[];
await rln.initRLNContract(rln.rlnInstance);
setWallet(accounts?.[0] || "");
} catch(error) {
console.error("Failed to conenct to wallet.");
}
};
return {
onWalletConnect,
};
};

6
src/lib/utils.ts Normal file
View File

@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

12
src/main.tsx Normal file
View File

@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './globals.css'
import { Toaster } from "@/components/ui/sonner"
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
<Toaster />
</React.StrictMode>,
)

View File

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

View File

@ -1,166 +0,0 @@
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_LOADED = "WASM Blob downloaded",
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 ethProvider: ethers.providers.Web3Provider | undefined;
public rlnInstance: undefined | RLNInstance;
public rlnContract: undefined | RLNContract;
public keystore: Keystore;
private initialized = false;
private initializing = false;
public constructor() {
this.keystore = this.initKeystore();
}
public async init(): Promise<void> {
if (this.initialized || this.initializing) {
return;
}
this.initializing = true;
this.initProvider();
await this.initRLNWasm();
// emit keystore keys once app is ready
this.emitKeystoreKeys();
this.initialized = true;
this.initializing = false;
}
private initProvider() {
if (typeof window === "undefined") {
return;
}
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");
}
private async initRLNWasm(): Promise<void> {
this.emitStatusEvent(StatusEventPayload.WASM_LOADING);
try {
this.rlnInstance = await create();
} catch (error) {
console.error(
"Failed at fetching WASM and creating RLN instance: ",
error
);
this.emitStatusEvent(StatusEventPayload.WASM_FAILED);
throw error;
}
this.emitStatusEvent(StatusEventPayload.WASM_LOADED);
}
public async initRLNContract(rlnInstance: RLNInstance): Promise<void> {
if (this.rlnContract || !this.ethProvider) {
return;
}
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;
}
this.emitStatusEvent(StatusEventPayload.RLN_INITIALIZED);
}
private initKeystore(): Keystore {
const localKeystoreString = localStorage.getItem("keystore");
if (!localKeystoreString) {
return Keystore.create();
}
try {
return Keystore.fromString(localKeystoreString || "") || Keystore.create();
} catch(error) {
return 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,203 +0,0 @@
import { PUBSUB_TOPIC, SUPPORTED_PUBSUB_TOPICS } 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 RELAY = "/relay/v1";
const buildURL = (endpoint: string) => `${LOCAL_NODE}${endpoint}`;
class Relay {
private activePubsubTopic = SUPPORTED_PUBSUB_TOPICS[0];
private subscribing = false;
private readonly subscriptionsEmitter = new EventTarget();
// only one content topic subscriptions is possible now
private subscriptionRoutine: undefined | number;
constructor() {}
public addEventListener(contentTopic: string, fn: EventListener) {
this.subscribe();
return this.subscriptionsEmitter.addEventListener(contentTopic, fn as any);
}
public removeEventListener(contentTopic: string, fn: EventListener) {
return this.subscriptionsEmitter.removeEventListener(
contentTopic,
fn as any
);
}
private async subscribe() {
if (this.subscriptionRoutine || this.subscribing) {
return;
}
this.subscribing = true;
try {
await http.post(buildURL(`${RELAY}/subscriptions`), SUPPORTED_PUBSUB_TOPICS);
this.subscriptionRoutine = window.setInterval(async () => {
await this.fetchMessages();
}, 5 * SECOND);
} catch (error) {
console.error(`Failed to subscribe node any of ${SUPPORTED_PUBSUB_TOPICS}:`, error);
}
this.subscribing = false;
}
public async unsubscribe() {
if (!this.subscriptionRoutine) {
return;
}
try {
await http.delete(buildURL(`${RELAY}/subscriptions`), [PUBSUB_TOPIC]);
} catch (error) {
console.error(`Failed to unsubscribe node from ${PUBSUB_TOPIC}:`, error);
}
clearInterval(this.subscriptionRoutine);
this.subscriptionRoutine = undefined;
}
private async fetchMessages(): Promise<void> {
const response = await http.get(
buildURL(`${RELAY}/messages/${encodeURIComponent(this.activePubsubTopic)}`)
);
const body: Message[] = await response.json();
if (!body || !body.length) {
return;
}
const messagesPerContentTopic = new Map<string, Message[]>();
body.forEach((m) => {
const contentTopic = m.contentTopic;
if (!contentTopic) {
return;
}
let messages = messagesPerContentTopic.get(contentTopic);
if (!messages) {
messages = [];
}
messages.push(m);
messagesPerContentTopic.set(contentTopic, messages);
});
Array.from(messagesPerContentTopic.entries()).forEach(([contentTopic, messages]) => {
this.subscriptionsEmitter.dispatchEvent(
new CustomEvent(contentTopic, { detail: messages })
);
});
}
public changeActivePubsubTopic(pubsubTopic: string) {
this.activePubsubTopic = pubsubTopic;
}
public async send(pubsubTopic: string, message: Message): Promise<void> {
await http.post(buildURL(`${RELAY}/messages/${encodeURIComponent(pubsubTopic)}`), message);
}
}
type DebugInfoResponse = {
enrUri: string;
listenAddresses: string[];
}
export type DebugInfo = {
health: string;
version: string;
} & DebugInfoResponse;
class Debug {
private subscribing = false;
private readonly subscriptionsEmitter = new EventTarget();
private subscriptionRoutine: undefined | number;
constructor() {}
public addEventListener(event: string, fn: EventListener) {
this.subscribe();
return this.subscriptionsEmitter.addEventListener(event, fn as any);
}
public removeEventListener(event: string, fn: EventListener) {
return this.subscriptionsEmitter.removeEventListener(
event,
fn as any
);
}
private async subscribe() {
if (this.subscriptionRoutine || this.subscribing) {
return;
}
this.subscribing = true;
try {
await this.fetchParameters();
this.subscriptionRoutine = window.setInterval(async () => {
await this.fetchParameters();
}, 30 * SECOND);
} catch(error) {
console.error("Failed to fetch debug info:", error);
}
this.subscribing = false;
}
private async unsubscribe() {
if (!this.subscriptionRoutine) {
return;
}
clearInterval(this.subscriptionRoutine);
this.subscriptionRoutine = undefined;
}
private async fetchParameters(): Promise<void> {
const health = await this.fetchHealth();
const debug = await this.fetchDebugInfo();
const version = await this.fetchDebugVersion();
this.subscriptionsEmitter.dispatchEvent(
new CustomEvent("debug", { detail: {
health,
version,
...debug,
} })
);
}
private async fetchHealth(): Promise<string> {
const response = await http.get(buildURL(`/health`));
return response.text();
}
private async fetchDebugInfo(): Promise<DebugInfoResponse> {
const response = await http.get(buildURL(`/debug/v1/info`));
const body: DebugInfoResponse = await response.json();
return body;
}
private async fetchDebugVersion(): Promise<string> {
const response = await http.get(buildURL(`/debug/v1/version`));
return response.text();
}
}
export const waku = {
relay: new Relay(),
debug: new Debug(),
};

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

@ -1,25 +0,0 @@
export const http = {
post(url: string, body: any) {
return fetch(new URL(url), {
method: "POST",
mode: "no-cors",
referrerPolicy: "no-referrer",
headers: {
'Content-Type': 'text/plain',
},
body: JSON.stringify(body)
});
},
delete(url: string, body: any) {
return fetch(new URL(url), {
method: "DELETE",
headers: {
'Content-Type': 'text/plain',
},
body: JSON.stringify(body)
});
},
get(url: string) {
return fetch(new URL(url));
}
};

1
src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

77
tailwind.config.js Normal file
View File

@ -0,0 +1,77 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
}

View File

@ -1,27 +1,32 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
"@/*": [
"./src/*"
]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

11
tsconfig.node.json Normal file
View File

@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}

13
vite.config.ts Normal file
View File

@ -0,0 +1,13 @@
import path from "path"
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})