feat(keystore_management): new app, setup wallet connection/management with sepolia (#114)

This commit is contained in:
Danish Arora 2025-02-27 11:56:05 +05:30 committed by GitHub
parent a0913960ca
commit cdd74f9f56
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 8468 additions and 1 deletions

View File

@ -22,7 +22,8 @@ jobs:
dogfooding,
message-monitor,
flush-notes,
buddybook
buddybook,
keystore-management
]
runs-on: ubuntu-latest
steps:

41
examples/keystore-management/.gitignore vendored Normal file
View File

@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@ -0,0 +1,45 @@
# Waku Keystore Management
A simple Next.js application to manage Waku RLN keystores.
## Overview
This application provides an interface for managing keystores for Waku's rate-limiting nullifier (RLN) functionality. It integrates with MetaMask for wallet connectivity and demonstrates how to work with the Waku RLN library.
## Features
- Connect to MetaMask wallet
- View wallet information including address, network, and balance
- Support for Sepolia testnet
- Keystore management functionality
## Getting Started
1. First, install the dependencies:
```bash
npm install
# or
yarn
```
2. Run the development server:
```bash
npm run dev
# or
yarn dev
```
3. Open [http://localhost:3000](http://localhost:3000) with your browser.
4. Connect your MetaMask wallet (Sepolia testnet is supported).
## Technologies
- Next.js
- React
- TypeScript
- TailwindCSS
- Waku RLN library
- Ethers.js

View File

@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;

View File

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
{
"name": "waku-keystore-management",
"version": "0.1.0",
"private": true,
"description": "A simple application to manage Waku RLN keystores",
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@waku/rln": "0.0.2-c41b319.0",
"next": "15.1.7",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.1.7",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}

View File

@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

View File

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@ -0,0 +1,21 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}

View File

@ -0,0 +1,43 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { WalletProvider } from "../contexts/WalletContext";
import { Header } from "../components/Header";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Waku Keystore Management",
description: "Manage your Waku RLN keystores securely",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<WalletProvider>
<div className="flex flex-col min-h-screen">
<Header />
<main className="flex-grow">
{children}
</main>
</div>
</WalletProvider>
</body>
</html>
);
}

View File

@ -0,0 +1,12 @@
export default function Home() {
return (
<div className="container mx-auto px-4 py-8">
<div className="max-w-4xl mx-auto">
<div className="bg-white rounded-lg shadow-md dark:bg-gray-800 p-6">
<h2 className="text-2xl font-bold text-center text-gray-900 dark:text-white">Waku Keystore Management</h2>
{/* Your keystore management content will go here */}
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,19 @@
"use client";
import React from 'react';
import { WalletInfo } from './WalletInfo';
export function Header() {
return (
<header className="sticky top-0 z-10 bg-white dark:bg-gray-900 shadow-sm">
<div className="container mx-auto px-4 py-3 flex justify-between items-center">
<div className="flex items-center">
<h1 className="text-xl font-bold text-gray-900 dark:text-white">Waku Keystore Management</h1>
</div>
<div className="w-80">
<WalletInfo />
</div>
</div>
</header>
);
}

View File

@ -0,0 +1,133 @@
"use client";
import React from 'react';
import { useWallet } from '../contexts/WalletContext';
function getNetworkName(chainId: number | null): string {
if (!chainId) return 'Unknown';
switch (chainId) {
case 11155111: return 'Sepolia Testnet (Supported)';
default: return `Unsupported Network (Chain ID: ${chainId})`;
}
}
// Sepolia Chain ID
const SEPOLIA_CHAIN_ID = '0xaa36a7'; // 11155111 in hex
// Define interface for provider errors
interface ProviderRpcError extends Error {
code: number;
data?: unknown;
}
export function WalletInfo() {
const { isConnected, address, balance, chainId, connectWallet, disconnectWallet, error } = useWallet();
// Function to switch to Sepolia network
const switchToSepolia = async () => {
if (!window.ethereum) {
console.error("MetaMask not installed");
return;
}
try {
// Try to switch to Sepolia
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: SEPOLIA_CHAIN_ID }],
});
} catch (err) {
// If the error code is 4902, the chain hasn't been added to MetaMask
const providerError = err as ProviderRpcError;
if (providerError.code === 4902) {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: SEPOLIA_CHAIN_ID,
chainName: 'Sepolia Testnet',
nativeCurrency: {
name: 'Sepolia ETH',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://sepolia.infura.io/v3/'],
blockExplorerUrls: ['https://sepolia.etherscan.io'],
},
],
});
} catch (addError) {
console.error("Error adding Sepolia chain", addError);
}
} else {
console.error("Error switching to Sepolia chain", providerError);
}
}
};
// Check if user is on unsupported network
const isUnsupportedNetwork = isConnected && chainId !== 11155111;
return (
<div className="bg-white rounded-lg shadow-sm dark:bg-gray-800 p-3">
{error && (
<div className="mb-2 p-2 text-xs bg-red-100 text-red-700 rounded-md dark:bg-red-900 dark:text-red-100">
<p>{error}</p>
</div>
)}
{isConnected ? (
<div className="flex flex-col">
<div className="flex items-center justify-between mb-2">
<div className="mr-3">
<div className="flex items-center mb-1">
<span className="text-xs text-gray-500 dark:text-gray-400 mr-1">Address:</span>
<span className="font-mono text-xs text-gray-900 dark:text-white truncate max-w-[120px]">
{address}
</span>
</div>
<div className="flex items-center mb-1">
<span className="text-xs text-gray-500 dark:text-gray-400 mr-1">Network:</span>
<span className={`font-mono text-xs ${isUnsupportedNetwork ? 'text-orange-600 dark:text-orange-400' : 'text-gray-900 dark:text-white'}`}>
{getNetworkName(chainId)}
</span>
</div>
<div className="flex items-center">
<span className="text-xs text-gray-500 dark:text-gray-400 mr-1">Balance:</span>
<span className="font-mono text-xs text-gray-900 dark:text-white">
{balance ? `${parseFloat(balance).toFixed(4)} ETH` : 'Loading...'}
</span>
</div>
</div>
<button
onClick={disconnectWallet}
className="px-2 py-1 text-xs bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
>
Disconnect
</button>
</div>
{isUnsupportedNetwork && (
<button
onClick={switchToSepolia}
className="w-full mt-1 px-2 py-1 text-xs bg-orange-500 text-white rounded-md hover:bg-orange-600 transition-colors"
>
Switch to Sepolia
</button>
)}
</div>
) : (
<div className="flex items-center justify-center">
<button
onClick={connectWallet}
className="px-3 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
>
Connect Wallet
</button>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,164 @@
"use client";
import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
import { extractMetaMaskSigner } from '@waku/rln';
import { ethers } from 'ethers';
interface WalletContextType {
isConnected: boolean;
address: string | null;
signer: ethers.Signer | null;
balance: string | null;
chainId: number | null;
connectWallet: () => Promise<void>;
disconnectWallet: () => void;
error: string | null;
}
const WalletContext = createContext<WalletContextType | undefined>(undefined);
export function WalletProvider({ children }: { children: ReactNode }) {
const [isConnected, setIsConnected] = useState(false);
const [address, setAddress] = useState<string | null>(null);
const [signer, setSigner] = useState<ethers.Signer | null>(null);
const [balance, setBalance] = useState<string | null>(null);
const [chainId, setChainId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
// Function to disconnect wallet - defined first to avoid reference issues
const disconnectWallet = useCallback(() => {
setSigner(null);
setAddress(null);
setBalance(null);
setChainId(null);
setIsConnected(false);
// Event listeners are removed in the cleanup function of useEffect
}, []);
// Function to connect wallet
const connectWallet = useCallback(async () => {
try {
setError(null);
const signer = await extractMetaMaskSigner();
setSigner(signer);
const address = await signer.getAddress();
setAddress(address);
const provider = signer.provider as ethers.providers.Web3Provider;
const network = await provider.getNetwork();
setChainId(network.chainId);
const balanceWei = await provider.getBalance(address);
const balanceEth = ethers.utils.formatEther(balanceWei);
setBalance(balanceEth);
setIsConnected(true);
} catch (err) {
console.error('Error connecting wallet:', err);
setError(err instanceof Error ? err.message : 'Failed to connect wallet');
disconnectWallet();
}
}, [disconnectWallet]);
// Handle account changes
const handleAccountsChanged = useCallback((accounts: string[]) => {
if (accounts.length === 0) {
disconnectWallet();
} else if (accounts[0] !== address) {
connectWallet();
}
}, [address, connectWallet, disconnectWallet]);
// Handle chain changes
const handleChainChanged = useCallback(() => {
connectWallet();
}, [connectWallet]);
// Setup and cleanup event listeners
useEffect(() => {
if (window.ethereum && isConnected) {
window.ethereum.on('accountsChanged', handleAccountsChanged);
window.ethereum.on('chainChanged', handleChainChanged as (chainId: string) => void);
}
return () => {
if (window.ethereum) {
window.ethereum.removeListener('accountsChanged', handleAccountsChanged);
window.ethereum.removeListener('chainChanged', handleChainChanged as (chainId: string) => void);
}
};
}, [handleAccountsChanged, handleChainChanged, isConnected]);
// Check if wallet was previously connected
useEffect(() => {
const checkConnection = async () => {
try {
// Check if MetaMask is installed
if (!window.ethereum) {
console.log("MetaMask not installed");
return;
}
// Check if already connected
const accounts = await window.ethereum.request({
method: 'eth_accounts'
}) as string[];
if (accounts && accounts.length > 0) {
console.log("Found existing connection, reconnecting...");
connectWallet();
} else {
console.log("No existing connection found");
}
} catch (error) {
console.error("Error checking for existing connection:", error);
}
};
checkConnection();
}, [connectWallet]);
return (
<WalletContext.Provider
value={{
isConnected,
address,
signer,
balance,
chainId,
connectWallet,
disconnectWallet,
error
}}
>
{children}
</WalletContext.Provider>
);
}
export function useWallet() {
const context = useContext(WalletContext);
if (context === undefined) {
throw new Error('useWallet must be used within a WalletProvider');
}
return context;
}
declare global {
interface Window {
ethereum?: {
isMetaMask?: boolean;
isConnected?: boolean;
selectedAddress?: string;
request: (args: { method: string; params?: unknown[] }) => Promise<unknown>;
on(event: 'accountsChanged', listener: (accounts: string[]) => void): void;
on(event: 'chainChanged', listener: (chainId: string) => void): void;
on(event: string, listener: (...args: unknown[]) => void): void;
removeListener(event: 'accountsChanged', listener: (accounts: string[]) => void): void;
removeListener(event: 'chainChanged', listener: (chainId: string) => void): void;
removeListener(event: string, listener: (...args: unknown[]) => void): void;
};
}
}

View File

@ -0,0 +1,18 @@
import type { Config } from "tailwindcss";
export default {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
} satisfies Config;

View File

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