feat: re-work rln-js (#281)

* use next.js tempalte

* use next lint rules

* alight UI

* fix problem with margins

* remove old page, rename to hooks

* add constants

* create RLN service, add utils

* add RLN init

* refactor a bit

* add init for Keystore

* add store functions

* add styles

* add contract hooks, add store fields, fix multiple downloads issue

* add features

* add keystore read logic

* add import export

* combine to useContract

* add useWaku stub, add state to Waku block, styles

* add creation of a node

* add messages functionality

* up readme

* update CI

* update readme

* remove and rename, address comments

* update readme

* move const
This commit is contained in:
Sasha 2023-11-20 19:00:11 +03:00 committed by GitHub
parent b753794bdc
commit 85d8156b7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 17015 additions and 1455 deletions

View File

@ -5,12 +5,11 @@
"es2021": true,
"node": true
},
"extends": "plugin:react/recommended",
"extends": "next/core-web-vitals",
"overrides": [],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest"
},
"plugins": ["react", "@typescript-eslint"],
"rules": {}
}

12
ci/Jenkinsfile vendored
View File

@ -43,6 +43,7 @@ pipeline {
stage('noise-js') { steps { script { buildExample() } } }
stage('noise-rtc') { steps { script { buildExample() } } }
stage('relay-direct-rtc') { steps { script { buildExample() } } }
stage('rln-js') { steps { script { buildNextJSExample() } } }
}
}
@ -51,7 +52,6 @@ pipeline {
stage('relay-js') { steps { script { copyExample() } } }
stage('store-js') { steps { script { copyExample() } } }
stage('light-js') { steps { script { copyExample() } } }
stage('rln-js') { steps { script { copyExample() } } }
stage('light-chat') { steps { script { copyExample() } } }
}
}
@ -86,3 +86,13 @@ def copyExample(example=STAGE_NAME) {
sh "mkdir -p ${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

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

35
examples/rln-js/.gitignore vendored Normal file
View File

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

View File

@ -12,17 +12,17 @@
- Retrieve smart contract state
- Generate and send proofs
- Verify incoming proofs
- Pure Javascript/HTML.
- Use minified bundle of js from unpkg.com, no import, no package manager.
- Keystore
- Next.js framework
To test the example:
# Getting Started
```shell
git clone https://github.com/waku-org/js-waku-examples
cd js-waku-examples/examples/rln-js
npm install
npm run start
# open http://127.0.0.1:8080 In your browser
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**.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

View File

@ -1,173 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>JS-Waku light node example</title>
<link
href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css"
rel="stylesheet"
/>
<link href="style.css" rel="stylesheet" />
<link rel="apple-touch-icon" href="./favicon.png" />
<link rel="manifest" href="./manifest.json" />
<link rel="icon" href="./favicon.ico" />
</head>
<body>
<div class="row rcenter">
<h1>Waku RLN</h1>
<button id="connect-wallet" type="button">Connect Wallet</button>
</div>
<span id="status"></span>
<h2 class="mu1">Blockchain</h2>
<hr />
<div class="row rcenter">
<h4>Address</h4>
<code class="value" id="address"></code>
</div>
<div class="row mu1 rcenter">
<h4>Contract Data</h4>
<button disabled id="retrieve-rln-details" type="button">
Retrieve contract state from blockchain
</button>
</div>
<div class="row rcenter">
<h4>Latest membership id on contract</h4>
<code class="value" id="latest-membership-id">Not loaded yet</code>
</div>
<div class="row rcenter mu1">
<div>
<h2>Keystore</h2>
<span id="keystoreStatus"></span>
</div>
<div>
<button id="importKeystore" type="button">Import json</button>
<input type="file" id="importKeystoreInput" style="display: none" />
<button id="exportKeystore" type="button">Download json</button>
</div>
</div>
<hr />
<div class="row mu1">
<label for="keystorePassword"
>Password(used for reading/saving into Keystore):</label
>
<input
id="keystorePassword"
name="keystorePassword"
type="text"
style="width: 100%"
/>
</div>
<div class="row">
<div class="w50">
<h4>Generate new credentials from wallet:</h4>
<br />
<button
id="import-from-wallet-button"
type="button"
style="width: 100%"
>
Generate new credentials
</button>
<br />
<button disabled id="register-button" type="button">
Register credentials
</button>
</div>
<div class="w50">
<h4>Read from Keystore:</h4>
<br />
<select
id="keystoreOptions"
style="
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
"
></select>
<br />
<button id="readKeystore" type="button">Read credentials</button>
</div>
</div>
<div class="row rcenter mu1">
<h4>Keystore Hash</h4>
<code class="value" id="keystoreHash">none</code>
</div>
<div class="row rcenter">
<h4>Membership id</h4>
<code class="value" id="id">none</code>
</div>
<div class="row rcenter">
<h4>Secret Hash</h4>
<code class="value" id="secret-hash">none</code>
</div>
<div class="row rcenter">
<h4>Commitment</h4>
<code class="value" id="commitment">none</code>
</div>
<div class="row rcenter">
<h4>Nullifier</h4>
<code class="value" id="nullifier">none</code>
</div>
<div class="row rcenter">
<h4>Trapdoor</h4>
<code class="value" id="trapdoor">none</code>
</div>
<h2 class="mu1">Waku</h2>
<hr />
<div id="waku-status"></div>
<div class="row rcenter mu1 mf">
<label for="remote-multiaddr">Remote peer's multiaddr</label>
<input
id="remote-multiaddr"
type="text"
value="/dns4/node-01.ac-cn-hongkong-c.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAkvWiyFsgRhuJEb9JfjYxEkoHLgnUQmr1N5mKWnYjxYRVm"
/>
<button disabled id="dial" type="button">Dial</button>
</div>
<div class="row rcenter mf">
<label for="nick-input">Your nickname</label>
<input
class="p100"
id="nick-input"
placeholder="Choose a nickname"
type="text"
/>
</div>
<div class="row rcenter mf">
<label for="textInput">Message text</label>
<input
class="p100"
disabled
id="textInput"
placeholder="Type your message here"
type="text"
/>
<button disabled id="sendButton" type="button">
Send message using Light Push
</button>
</div>
<span id="sending-status"></span>
<h4 class="mu1">Messages</h4>
<div id="messages"><ul id="messagesList"></ul></div>
<script src="https://unpkg.com/@multiformats/multiaddr@12.1.1/dist/index.min.js"></script>
<script type="module" src="./index.js"></script>
</body>
</html>

View File

@ -1,606 +0,0 @@
import * as utils from "https://unpkg.com/@waku/utils@0.0.10/bundle/bytes.js";
import {
createEncoder,
createDecoder,
waitForRemotePeer,
createLightNode,
} from "https://unpkg.com/@waku/sdk@0.0.18/bundle/index.js";
import { protobuf } from "https://taisukef.github.io/protobuf-es.js/dist/protobuf-es.js";
import {
create,
Keystore,
RLNDecoder,
RLNEncoder,
RLNContract,
SEPOLIA_CONTRACT,
} from "https://unpkg.com/@waku/rln@0.1.1-fa49e29/bundle/index.js";
import { ethers } from "https://unpkg.com/ethers@5.7.2/dist/ethers.esm.min.js";
const ContentTopic = "/toy-chat/2/luzhou/proto";
// Protobuf
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, "bytes"));
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";
run()
.then(() => {
console.log("Successfully started application.");
})
.catch((err) => {
console.error("Failed at starting application with ", err.message);
});
async function run() {
const ui = initUI();
const rln = await initRLN(ui);
await initWaku(ui, rln);
}
async function initRLN(ui) {
const result = {
encoder: undefined,
rlnInstance: undefined,
contract: undefined,
};
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
ui.setRlnStatus("WASM Blob download in progress...");
const rlnInstance = await create();
ui.setRlnStatus("WASM Blob download in progress... done!");
const rlnContract = await RLNContract.init(rlnInstance, {
registryAddress: SEPOLIA_CONTRACT.address,
provider: provider.getSigner(),
});
result.contract = rlnContract;
// Keystore logic
let keystore = initKeystore(ui);
ui.createKeystoreOptions(keystore);
ui.onKeystoreImport(async (text) => {
try {
keystore = Keystore.fromString(text);
ui.setKeystoreStatus("Imported keystore from json");
} catch (err) {
console.error("Failed to import keystore:", err);
ui.setKeystoreStatus("Failed to import, fallback to current keystore");
}
ui.createKeystoreOptions(keystore);
saveLocalKeystore(keystore);
});
ui.onKeystoreExport(async () => {
return keystore.toString();
});
ui.onKeystoreRead(async (hash, password) => {
return keystore.readCredential(hash, password);
});
// Wallet logic
window.ethereum.on("accountsChanged", ui.setAccount);
window.ethereum.on("chainChanged", (chainId) => {
const id = parseInt(chainId, 16);
ui.disableIfNotSepolia(id);
});
ui.onConnectWallet(async () => {
try {
const accounts = await provider.send("eth_requestAccounts", []);
ui.setAccount(accounts);
const network = await provider.getNetwork();
ui.disableIfNotSepolia(network.chainId);
} catch (e) {
console.log("No web3 provider available", e);
}
});
ui.onRetrieveDetails(async () => {
const filter = rlnContract.contract.filters.MemberRegistered();
ui.disableRetrieveButton();
await rlnContract.fetchMembers(rlnInstance);
ui.enableRetrieveButton();
rlnContract.subscribeToMembers(rlnInstance);
const last = rlnContract.members.at(-1);
if (last) {
ui.setLastMember(last.index, last.idCommitment);
}
// make sure we have subscriptions to keep updating last item
rlnContract.contract.on(filter, (_idCommitment, _index, event) => {
ui.setLastMember(event.args.index, event.args.idCommitment);
});
});
let signature;
let membershipId;
let credentials;
ui.onWalletImport(async () => {
const signer = provider.getSigner();
signature = await signer.signMessage(
`${SIGNATURE_MESSAGE}. Nonce: ${Math.ceil(Math.random() * 1000)}`
);
credentials = await rlnInstance.generateSeededIdentityCredential(signature);
const idCommitment = ethers.utils.hexlify(credentials.IDCommitment);
rlnContract.members.forEach((m) => {
if (m.idCommitment === idCommitment) {
membershipId = m.index.toString();
}
});
if (membershipId) {
result.encoder = new RLNEncoder(
createEncoder({
ephemeral: false,
contentTopic: ContentTopic,
}),
rlnInstance,
membershipId,
credentials
);
}
ui.setMembershipInfo(membershipId, credentials);
const network = await provider.getNetwork();
ui.enableRegisterButtonForSepolia(network.chainId);
});
ui.onRegister(async () => {
ui.setRlnStatus("Trying to register...");
const memberInfo = signature
? await rlnContract.registerWithSignature(rlnInstance, signature)
: await rlnContract.registerWithKey(credentials);
membershipId = memberInfo.index.toNumber();
console.log(
"Obtained index for current membership credentials",
membershipId
);
const password = ui.getKeystorePassword();
if (!password) {
ui.setKeystoreStatus("Cannot add credentials, no password.");
}
const keystoreHash = await keystore.addCredential(
{
membership: {
treeIndex: membershipId,
chainId: SEPOLIA_CONTRACT.chainId,
address: SEPOLIA_CONTRACT.address,
},
identity:
credentials ||
rlnInstance.generateSeededIdentityCredential(signature),
},
password
);
saveLocalKeystore(keystore);
ui.addKeystoreOption(keystoreHash);
ui.setKeystoreStatus(`Added credential to Keystore`);
ui.setRlnStatus("Successfully registered.");
ui.setMembershipInfo(membershipId, credentials, keystoreHash);
ui.enableDialButton();
});
return result;
}
async function initWaku(ui, rln) {
ui.setWakuStatus("Creating Waku node.");
const node = await createLightNode();
ui.setWakuStatus("Starting Waku node.");
await node.start();
ui.setWakuStatus("Waku node started.");
const verifyMessage = (message) => {
if (message.proofState === "verifying...") {
try {
console.log("Verifying proof without roots");
console.time("proof_verify_timer");
const res = message.verify(rln.contract.roots());
console.timeEnd("proof_verify_timer");
console.log("proof verified without roots", res);
if (res === undefined) {
message.proofState = "no proof attached";
} else if (res) {
message.proofState = "verified.";
} else {
message.proofState = "invalid!";
}
} catch (e) {
message.proofState = "Error encountered, check console";
console.error("Error verifying proof:", e);
}
console.log("Verifying proof with roots", message.verify());
}
};
const onFilterMessage = (wakuMessage) => {
const { timestamp, nick, text } = ProtoChatMessage.decode(
wakuMessage.payload
);
const time = new Date();
time.setTime(Number(timestamp) * 1000);
if (wakuMessage.rateLimitProof) {
console.log("Proof received:", wakuMessage.rateLimitProof);
}
wakuMessage.proofState = !!wakuMessage.rateLimitProof
? "verifying..."
: "no proof attached";
wakuMessage.msg = `
(${nick})
<strong>${utils.bytesToUtf8(text)}</strong>
<i>[${time.toISOString()}]</i>
`;
verifyMessage(wakuMessage);
ui.renderMessage(wakuMessage);
};
ui.onDial(async (ma) => {
ui.setWakuStatus("Dialing peer.");
// TODO(@weboko): move this fix into Waku.dial
const multiaddr = MultiformatsMultiaddr.multiaddr(ma);
await node.dial(multiaddr, ["filter", "lightpush"]);
await waitForRemotePeer(node, ["filter", "lightpush"]);
ui.setWakuStatus("Waku node connected.");
const decoder = new RLNDecoder(
rln.rlnInstance,
createDecoder(ContentTopic)
);
await node.filter.subscribe(decoder, onFilterMessage);
ui.setWakuStatus("Waku node subscribed.");
ui.enableChatButtonsIfNickSet();
});
ui.onSendMessage(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...");
ui.setSendingStatus("sending...");
await node.lightPush.send(rln.encoder, { payload, timestamp });
ui.setSendingStatus("sent!");
console.log("Message sent!");
ui.clearMessageArea();
});
}
function initUI() {
const statusSpan = document.getElementById("status");
// Blockchain Elements
const addressDiv = document.getElementById("address");
const connectWalletButton = document.getElementById("connect-wallet");
const latestMembershipSpan = document.getElementById("latest-membership-id");
const retrieveRLNDetailsButton = document.getElementById(
"retrieve-rln-details"
);
const importFromWalletButton = document.getElementById(
"import-from-wallet-button"
);
const keystoreHashDiv = document.getElementById("keystoreHash");
const idDiv = document.getElementById("id");
const secretHashDiv = document.getElementById("secret-hash");
const commitmentDiv = document.getElementById("commitment");
const trapdoorDiv = document.getElementById("trapdoor");
const nullifierDiv = document.getElementById("nullifier");
const registerButton = document.getElementById("register-button");
// Waku Elements
const statusDiv = document.getElementById("waku-status");
const remoteMultiAddrInput = document.getElementById("remote-multiaddr");
const dialButton = document.getElementById("dial");
const nicknameInput = document.getElementById("nick-input");
const textInput = document.getElementById("textInput");
const sendButton = document.getElementById("sendButton");
const sendingStatusSpan = document.getElementById("sending-status");
const messagesList = document.getElementById("messagesList");
// Keystore
const importKeystoreBtn = document.getElementById("importKeystore");
const importKeystoreInput = document.getElementById("importKeystoreInput");
const exportKeystore = document.getElementById("exportKeystore");
const keystoreStatus = document.getElementById("keystoreStatus");
const keystorePassword = document.getElementById("keystorePassword");
const keystoreOptions = document.getElementById("keystoreOptions");
const readKeystoreButton = document.getElementById("readKeystore");
// set initial state
keystoreHashDiv.innerText = "not registered yet";
idDiv.innerText = "not registered yet";
registerButton.disabled = true;
textInput.disabled = true;
sendButton.disabled = true;
dialButton.disabled = true;
retrieveRLNDetailsButton.disabled = true;
nicknameInput.disabled = true;
nicknameInput.onchange = enableChatIfNeeded;
nicknameInput.onblur = enableChatIfNeeded;
function enableChatIfNeeded() {
if (nicknameInput.value) {
textInput.disabled = false;
sendButton.disabled = false;
}
}
// Keystore
keystorePassword.onchange = enableRegisterIfNeeded;
keystorePassword.onblur = enableRegisterIfNeeded;
function enableRegisterIfNeeded() {
if (keystorePassword.value && commitmentDiv.innerText !== "none") {
registerButton.disabled = false;
}
}
return {
// UI for RLN
setRlnStatus(text) {
statusSpan.innerText = text;
},
setMembershipInfo(id, credential, keystoreHash) {
keystoreHashDiv.innerText = keystoreHash || "not registered yet";
idDiv.innerText = id || "not registered yet";
secretHashDiv.innerText = utils.bytesToHex(credential.IDSecretHash);
commitmentDiv.innerText = utils.bytesToHex(credential.IDCommitment);
nullifierDiv.innerText = utils.bytesToHex(credential.IDNullifier);
trapdoorDiv.innerText = utils.bytesToHex(credential.IDTrapdoor);
},
setLastMember(index, _idCommitment) {
try {
const idCommitment = ethers.utils.zeroPad(
ethers.utils.arrayify(_idCommitment),
32
);
const indexInt = index.toNumber();
console.debug(
"IDCommitment registered in tree",
idCommitment,
indexInt
);
latestMembershipSpan.innerHTML = indexInt;
} catch (err) {
console.error(err); // TODO: the merkle tree can be in a wrong state. The app should be disabled
}
},
disableIfNotSepolia(chainId) {
if (!isSepolia(chainId)) {
window.alert("Switch to Sepolia");
registerButton.disabled = true;
this.disableRetrieveButton();
} else {
this.enableRetrieveButton();
}
},
enableRetrieveButton() {
retrieveRLNDetailsButton.disabled = false;
},
disableRetrieveButton() {
retrieveRLNDetailsButton.disabled = true;
},
enableRegisterButtonForSepolia(chainId) {
registerButton.disabled =
isSepolia(chainId) &&
keystorePassword.value &&
commitmentDiv.innerText !== "none"
? false
: true;
},
getKeystorePassword() {
return keystorePassword.value;
},
setAccount(accounts) {
addressDiv.innerText = accounts.length ? accounts[0] : "";
},
onConnectWallet(fn) {
connectWalletButton.addEventListener("click", async () => {
await fn();
importFromWalletButton.disabled = false;
});
},
onRetrieveDetails(fn) {
retrieveRLNDetailsButton.addEventListener("click", async () => {
await fn();
});
},
onWalletImport(fn) {
importFromWalletButton.addEventListener("click", async () => {
await fn();
});
},
onRegister(fn) {
registerButton.addEventListener("click", async () => {
try {
registerButton.disabled = true;
await fn();
registerButton.disabled = false;
} catch (err) {
alert(err);
registerButton.disabled = false;
}
});
},
// Keystore
addKeystoreOption(id) {
const option = document.createElement("option");
option.innerText = id;
option.setAttribute("value", id);
keystoreOptions.appendChild(option);
},
createKeystoreOptions(keystore) {
const ids = Object.keys(keystore.toObject().credentials || {});
keystoreOptions.innerHTML = "";
ids.forEach((v) => this.addKeystoreOption(v));
},
onKeystoreRead(fn) {
readKeystoreButton.addEventListener("click", async (event) => {
event.preventDefault();
if (!keystoreOptions.value) {
throw Error("No value selected to read from Keystore");
}
const credentials = await fn(
keystoreOptions.value,
keystorePassword.value
);
this.setMembershipInfo(
credentials.membership.treeIndex,
credentials.identity,
keystoreOptions.value
);
});
},
setKeystoreStatus(text) {
keystoreStatus.innerText = text;
},
onKeystoreImport(fn) {
importKeystoreBtn.addEventListener("click", (event) => {
event.preventDefault();
importKeystoreInput.click();
});
importKeystoreInput.addEventListener("change", async (event) => {
const file = event.target.files[0];
if (!file) {
console.error("No file selected");
return;
}
const text = await file.text();
fn(text);
});
},
onKeystoreExport(fn) {
exportKeystore.addEventListener("click", async (event) => {
event.preventDefault();
const filename = "keystore.json";
const text = await fn();
const file = new File([text], filename, {
type: "application/json",
});
const link = document.createElement("a");
link.href = URL.createObjectURL(file);
link.download = filename;
link.click();
});
},
// UI for Waku
setWakuStatus(text) {
statusDiv.innerText = text;
},
setSendingStatus(text) {
sendingStatusSpan.innerText = text;
},
renderMessage(message) {
messagesList.innerHTML += `<li>${message.msg} - [epoch: ${message.epoch}, proof: ${message.proofState} ]</li>`;
},
enableDialButton() {
dialButton.disabled = false;
},
enableChatButtonsIfNickSet() {
if (nicknameInput.value) {
textInput.disabled = false;
sendButton.disabled = false;
}
},
onDial(fn) {
dialButton.addEventListener("click", async () => {
const multiaddr = remoteMultiAddrInput.value;
if (!multiaddr) {
this.setWakuStatus("Error: No multiaddr provided.");
return;
}
await fn(multiaddr);
nicknameInput.disabled = false;
});
},
clearMessageArea() {
textInput.value = null;
setTimeout(() => {
this.setSendingStatus("");
}, 5000);
},
onSendMessage(fn) {
sendButton.addEventListener("click", async () => {
const nick = nicknameInput.value;
const text = utils.utf8ToBytes(textInput.value);
await fn(nick, text);
});
},
};
}
function isSepolia(id) {
return id === 11155111;
}
function initKeystore(ui) {
try {
const text = readLocalKeystore();
if (!text) {
ui.setKeystoreStatus("Initialized empty keystore");
return Keystore.create();
}
const keystore = Keystore.fromString(text);
if (!keystore) {
throw Error("Failed to create from string");
}
ui.setKeystoreStatus("Loaded from localStorage");
return keystore;
} catch (err) {
console.error("Failed to init keystore:", err);
ui.setKeystoreStatus("Initialized empty keystore");
return Keystore.create();
}
}
function readLocalKeystore() {
return localStorage.getItem("keystore");
}
function saveLocalKeystore(keystore) {
localStorage.setItem("keystore", keystore.toString());
}

View File

@ -1,19 +0,0 @@
{
"name": "Waku RLN",
"description": "Use RLN in the browser, compatible with nwaku chat2 and go-waku chat2 RLN implementations.",
"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"
}

5
examples/rln-js/next-env.d.ts vendored Normal file
View File

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

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

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,35 @@
{
"name": "@waku/rln-js-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"name": "rln-js",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "http-server"
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@waku/rln": "0.1.1-7e8cb89",
"@waku/sdk": "^0.0.20",
"@waku/utils": "^0.0.12",
"ethers": "^5.7.2",
"multiaddr": "^10.0.1",
"next": "13.5.6",
"protobufjs": "^7.2.5",
"react": "^18",
"react-dom": "^18",
"zustand": "^4.4.4"
},
"keywords": [],
"author": "",
"license": "MIT OR Apache-2.0",
"devDependencies": {
"http-server": "^14.1.1"
"@metamask/types": "^1.1.0",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10",
"eslint": "^8",
"eslint-config-next": "13.5.6",
"postcss": "^8",
"tailwindcss": "^3",
"typescript": "^5"
}
}

View File

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

View File

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

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

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

View File

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

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

View File

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

View File

@ -1,51 +0,0 @@
html {
scroll-behavior: smooth;
}
h1 {
margin: 1rem 2.5rem 1rem 0;
}
.value {
font-size: 1.3em;
}
body > footer {
text-align: right;
}
.row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.rcenter {
align-items: center;
}
.mu1 {
margin-top: 4em;
}
.w50 {
width: 46%;
}
.w30 {
width: 35%;
}
.w70 {
width: 60%;
}
.mf label {
width: 100%;
}
.mf input {
width: 80%;
}
.mf input.p100 {
width: 100%;
}

View File

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

View File

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

2181
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"eslint": "^8.29.0",
"eslint-plugin-react": "^7.31.11",
"eslint-config-next": "13.5.6",
"husky": "^8.0.0",
"prettier": "^2.8.1",
"pretty-quick": "^3.1.3",