Merge branch 'master' into danisharora/credentials-from-wallet

This commit is contained in:
Danish Arora 2022-12-12 10:30:14 +05:30 committed by GitHub
commit 561eb60a57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 1910 additions and 414 deletions

16
.eslintrc.json Normal file
View File

@ -0,0 +1,16 @@
{
"env": {
"browser": true,
"commonjs": true,
"es2021": true,
"node": true
},
"extends": "plugin:react/recommended",
"overrides": [],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest"
},
"plugins": ["react", "@typescript-eslint"],
"rules": {}
}

1
.husky/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
_

4
.husky/pre-commit Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpx lint-staged

View File

@ -1,39 +1,43 @@
const { promisify } = require('util')
const { publish } = require('gh-pages')
const ghpublish = promisify(publish)
const { promisify } = require("util");
const { publish } = require("gh-pages");
const ghpublish = promisify(publish);
/* fix for "Unhandled promise rejections" */
process.on('unhandledRejection', err => { throw err })
process.on("unhandledRejection", (err) => {
throw err;
});
const Args = process.argv.slice(2)
const USE_HTTPS = Args[0] && Args[0].toUpperCase() === 'HTTPS'
const Args = process.argv.slice(2);
const USE_HTTPS = Args[0] && Args[0].toUpperCase() === "HTTPS";
const branch = 'gh-pages'
const org = 'waku-org'
const repo = 'js-waku-examples'
const branch = "gh-pages";
const org = "waku-org";
const repo = "js-waku-examples";
/* use SSH auth by default */
let repoUrl = USE_HTTPS
? `https://github.com/${org}/${repo}.git`
: `git@github.com:${org}/${repo}.git`
: `git@github.com:${org}/${repo}.git`;
/* alternative auth using GitHub user and API token */
if (process.env.GH_USER != undefined) {
repoUrl = (
'https://' + process.env.GH_USER +
':' + process.env.GH_TOKEN +
'@' + `github.com/${org}/${repo}.git`
)
repoUrl =
"https://" +
process.env.GH_USER +
":" +
process.env.GH_TOKEN +
"@" +
`github.com/${org}/${repo}.git`;
}
const main = async (url, branch)=> {
console.log(`Pushing to: ${url}`)
console.log(`On branch: ${branch}`)
await ghpublish('build/docs', {
const main = async (url, branch) => {
console.log(`Pushing to: ${url}`);
console.log(`On branch: ${branch}`);
await ghpublish("build/docs", {
repo: url,
branch: branch,
dotfiles: true,
silent: false
})
}
silent: false,
});
};
main(repoUrl, branch)
main(repoUrl, branch);

View File

@ -1,13 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

View File

@ -1,121 +1,129 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'/>
<meta content='width=device-width, initial-scale=1.0' name='viewport'/>
<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>
</head>
</head>
<body>
<body>
<div><h2>Status</h2></div>
<div id="status"></div>
<div><h2>Status</h2></div>
<div id='status'></div>
<div><h2>Local Peer Id</h2></div>
<div id="peer-id"></div>
<div><h2>Local Peer Id</h2></div>
<div id='peer-id'></div>
<div><h2>Remote Peer Id</h2></div>
<div id="remote-peer-id"></div>
<div><h2>Remote Peer Id</h2></div>
<div id='remote-peer-id'></div>
<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>
<br />
<button disabled id="subscribe" type="button">Subscribe with Filter</button>
<button disabled id="unsubscribe" type="button">
Unsubscribe with Filter
</button>
<br />
<label for="textInput">Message text</label>
<input id="textInput" placeholder="Type your message here" type="text" />
<button disabled id="sendButton" type="button">
Send message using Light Push
</button>
<br />
<div id="messages"></div>
<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>
<br/>
<button disabled id='subscribe' type='button'>Subscribe with Filter</button>
<button disabled id='unsubscribe' type='button'>Unsubscribe with Filter</button>
<br/>
<label for='textInput'>Message text</label>
<input id='textInput' placeholder='Type your message here' type='text'>
<button disabled id='sendButton' type='button'>Send message using Light Push</button>
<br/>
<div id="messages"></div>
<script type="module">
import * as utils from "https://unpkg.com/@waku/byte-utils@0.0.2/bundle/index.js";
import { createLightNode } from "https://unpkg.com/@waku/create@0.0.4/bundle/index.js";
import { waitForRemotePeer } from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/wait_for_remote_peer.js";
import {
EncoderV0,
DecoderV0,
} from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/waku_message/version_0.js";
<script type='module'>
import * as utils from 'https://unpkg.com/@waku/byte-utils@0.0.2/bundle/index.js';
import {createLightNode} from 'https://unpkg.com/@waku/create@0.0.4/bundle/index.js'
import {waitForRemotePeer} from 'https://unpkg.com/@waku/core@0.0.6/bundle/lib/wait_for_remote_peer.js'
import {EncoderV0, DecoderV0} from 'https://unpkg.com/@waku/core@0.0.6/bundle/lib/waku_message/version_0.js'
const peerIdDiv = document.getElementById("peer-id");
const remotePeerIdDiv = document.getElementById("remote-peer-id");
const statusDiv = document.getElementById("status");
const remoteMultiAddrDiv = document.getElementById("remote-multiaddr");
const dialButton = document.getElementById("dial");
const subscribeButton = document.getElementById("subscribe");
const unsubscribeButton = document.getElementById("unsubscribe");
const messagesDiv = document.getElementById("messages");
const textInput = document.getElementById("textInput");
const sendButton = document.getElementById("sendButton");
const peerIdDiv = document.getElementById('peer-id');
const remotePeerIdDiv = document.getElementById('remote-peer-id');
const statusDiv = document.getElementById('status');
const remoteMultiAddrDiv = document.getElementById('remote-multiaddr');
const dialButton = document.getElementById('dial')
const subscribeButton = document.getElementById('subscribe')
const unsubscribeButton = document.getElementById('unsubscribe')
const messagesDiv = document.getElementById('messages')
const textInput = document.getElementById('textInput');
const sendButton = document.getElementById('sendButton');
const ContentTopic = "/js-waku-examples/1/chat/utf8";
const decoder = new DecoderV0(ContentTopic);
const encoder = new EncoderV0(ContentTopic);
let messages = [];
let unsubscribe;
const ContentTopic = "/js-waku-examples/1/chat/utf8";
const decoder = new DecoderV0(ContentTopic);
const encoder = new EncoderV0(ContentTopic);
let messages = [];
let unsubscribe;
const updateMessages = (msgs, div) => {
div.innerHTML = "<ul>";
messages.forEach((msg) => (div.innerHTML += "<li>" + msg + "</li>"));
div.innerHTML += "</ul>";
};
const updateMessages = (msgs, div) => {
div.innerHTML = "<ul>"
messages.forEach(msg => div.innerHTML += "<li>" + msg + "</li>")
div.innerHTML += "</ul>"
}
statusDiv.innerHTML = "<p>Creating Waku node.</p>";
const node = await createLightNode();
statusDiv.innerHTML = '<p>Creating Waku node.</p>';
const node = await createLightNode();
statusDiv.innerHTML = "<p>Starting Waku node.</p>";
await node.start();
statusDiv.innerHTML = "<p>Waku node started.</p>";
peerIdDiv.innerHTML = "<p>" + node.libp2p.peerId.toString() + "</p>";
dialButton.disabled = false;
statusDiv.innerHTML = '<p>Starting Waku node.</p>';
await node.start();
statusDiv.innerHTML = '<p>Waku node started.</p>';
peerIdDiv.innerHTML = '<p>' + node.libp2p.peerId.toString() + '</p>'
dialButton.disabled = false;
dialButton.onclick = async () => {
const ma = remoteMultiAddrDiv.value
dialButton.onclick = async () => {
const ma = remoteMultiAddrDiv.value;
if (!ma) {
statusDiv.innerHTML = '<p>Error: No multiaddr provided.</p>';
return;
statusDiv.innerHTML = "<p>Error: No multiaddr provided.</p>";
return;
}
statusDiv.innerHTML = '<p>Dialing peer.</p>';
await node.dial(ma, ["filter", "lightpush"])
statusDiv.innerHTML = "<p>Dialing peer.</p>";
await node.dial(ma, ["filter", "lightpush"]);
await waitForRemotePeer(node, ["filter", "lightpush"]);
const peers = await node.libp2p.peerStore.all();
statusDiv.innerHTML = '<p>Peer dialed.</p>';
remotePeerIdDiv.innerHTML = '<p>' + peers[0].id.toString() + '</p>'
statusDiv.innerHTML = "<p>Peer dialed.</p>";
remotePeerIdDiv.innerHTML = "<p>" + peers[0].id.toString() + "</p>";
textInput.disabled = false;
sendButton.disabled = false;
subscribeButton.disabled = false;
}
};
const callback = (wakuMessage) => {
const text = utils.bytesToUtf8(wakuMessage.payload)
const timestamp = wakuMessage.timestamp.toString()
messages.push(text + " - " + timestamp)
updateMessages(messages, messagesDiv)
}
const callback = (wakuMessage) => {
const text = utils.bytesToUtf8(wakuMessage.payload);
const timestamp = wakuMessage.timestamp.toString();
messages.push(text + " - " + timestamp);
updateMessages(messages, messagesDiv);
};
subscribeButton.onclick = async () => {
unsubscribe = await node.filter.subscribe([decoder], callback)
subscribeButton.onclick = async () => {
unsubscribe = await node.filter.subscribe([decoder], callback);
unsubscribeButton.disabled = false;
subscribeButton.disabled = true;
}
};
unsubscribeButton.onclick = async () => {
unsubscribeButton.onclick = async () => {
await unsubscribe();
unsubscribe = undefined
unsubscribe = undefined;
unsubscribeButton.disabled = true;
subscribeButton.disabled = false;
}
};
sendButton.onclick = async () => {
sendButton.onclick = async () => {
const text = textInput.value;
await node.lightPush.push(encoder, {payload: utils.utf8ToBytes(text)});
console.log('Message sent!');
await node.lightPush.push(encoder, {
payload: utils.utf8ToBytes(text),
});
console.log("Message sent!");
textInput.value = null;
};
</script>
</body>
};
</script>
</body>
</html>

View File

@ -1,5 +1,22 @@
{
"dependencies": {
"gh-pages": "^4.0.0"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"eslint": "^8.29.0",
"eslint-plugin-react": "^7.31.11",
"husky": "^8.0.0",
"prettier": "^2.8.1",
"pretty-quick": "^3.1.3",
"typescript": "^4.9.4"
},
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"*.{html,css,js,ts,jsx,tsx,json}": "prettier --write",
"*.{js,ts}": "eslint --fix"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -21,13 +21,8 @@
"index": "src/index.html",
"main": "src/main.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"assets": ["src/favicon.ico", "src/assets"],
"styles": ["src/styles.css"],
"scripts": []
},
"configurations": {
@ -87,13 +82,8 @@
"main": "src/test.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"assets": ["src/favicon.ico", "src/assets"],
"styles": ["src/styles.css"],
"scripts": []
}
}

View File

@ -3,14 +3,14 @@
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
basePath: "",
frameworks: ["jasmine", "@angular-devkit/build-angular"],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
require("karma-jasmine"),
require("karma-chrome-launcher"),
require("karma-jasmine-html-reporter"),
require("karma-coverage"),
require("@angular-devkit/build-angular/plugins/karma"),
],
client: {
jasmine: {
@ -19,26 +19,23 @@ module.exports = function (config) {
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
clearContext: false, // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
suppressAll: true, // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/relay-angular-chat'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
dir: require("path").join(__dirname, "./coverage/relay-angular-chat"),
subdir: ".",
reporters: [{ type: "html" }, { type: "text-summary" }],
},
reporters: ['progress', 'kjhtml'],
reporters: ["progress", "kjhtml"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
browsers: ["Chrome"],
singleRun: false,
restartOnFileChange: true
restartOnFileChange: true,
});
};

View File

@ -1 +1 @@
declare module 'protons';
declare module "protons";

View File

@ -1,8 +1,7 @@
declare module "time-cache" {
interface ITimeCache {
put(key: string, value: any, validity: number): void;
get(key: string): any;
get(key: string): any;
has(key: string): boolean;
}
@ -11,5 +10,4 @@ declare module "time-cache" {
function TimeCache(options: object): TimeCache;
export = TimeCache;
}

View File

@ -1,18 +1,15 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { MessagesComponent } from './messages/messages.component';
import { TestBed } from "@angular/core/testing";
import { AppComponent } from "./app.component";
import { MessagesComponent } from "./messages/messages.component";
describe('AppComponent', () => {
describe("AppComponent", () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
AppComponent,
MessagesComponent
],
declarations: [AppComponent, MessagesComponent],
}).compileComponents();
});
xit('should create the app', () => {
xit("should create the app", () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
@ -21,13 +18,15 @@ describe('AppComponent', () => {
xit(`should have as title 'relay-angular-chat'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('relay-angular-chat');
expect(app.title).toEqual("relay-angular-chat");
});
xit('should render title', () => {
xit("should render title", () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.h1')?.textContent).toContain('relay-angular-chat');
expect(compiled.querySelector(".h1")?.textContent).toContain(
"relay-angular-chat"
);
});
});

View File

@ -1,22 +1,20 @@
import { Component } from '@angular/core';
import { WakuService } from './waku.service';
import { Component } from "@angular/core";
import { WakuService } from "./waku.service";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title: string = 'relay-angular-chat';
title: string = "relay-angular-chat";
wakuStatus!: string;
constructor(private wakuService: WakuService) {}
ngOnInit(): void {
this.wakuService.init();
this.wakuService.wakuStatus.subscribe(wakuStatus => {
this.wakuService.wakuStatus.subscribe((wakuStatus) => {
this.wakuStatus = wakuStatus;
});
}

View File

@ -1,17 +1,12 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MessagesComponent } from './messages/messages.component';
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from "./app.component";
import { MessagesComponent } from "./messages/messages.component";
@NgModule({
declarations: [
AppComponent,
MessagesComponent
],
imports: [
BrowserModule
],
declarations: [AppComponent, MessagesComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
bootstrap: [AppComponent],
})
export class AppModule { }
export class AppModule {}

View File

@ -1,4 +1,6 @@
<button (click)="sendMessage()" [disabled]="wakuStatus !== 'Connected'">Send Message</button>
<button (click)="sendMessage()" [disabled]="wakuStatus !== 'Connected'">
Send Message
</button>
<h2>Messages</h2>
<ul class="messages">
<li *ngFor="let message of messages">

View File

@ -1,15 +1,14 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MessagesComponent } from './messages.component';
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { MessagesComponent } from "./messages.component";
describe('MessagesComponent', () => {
describe("MessagesComponent", () => {
let component: MessagesComponent;
let fixture: ComponentFixture<MessagesComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MessagesComponent ]
})
.compileComponents();
declarations: [MessagesComponent],
}).compileComponents();
});
beforeEach(() => {
@ -18,7 +17,7 @@ describe('MessagesComponent', () => {
fixture.detectChanges();
});
xit('should create', () => {
xit("should create", () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,8 +1,8 @@
import { TestBed } from '@angular/core/testing';
import { TestBed } from "@angular/core/testing";
import { WakuService } from './waku.service';
import { WakuService } from "./waku.service";
describe('WakuService', () => {
describe("WakuService", () => {
let service: WakuService;
beforeEach(() => {
@ -10,7 +10,7 @@ describe('WakuService', () => {
service = TestBed.inject(WakuService);
});
it('should be created', () => {
it("should be created", () => {
expect(service).toBeTruthy();
});
});

View File

@ -1,3 +1,3 @@
export const environment = {
production: true
production: true,
};

View File

@ -3,7 +3,7 @@
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
production: false,
};
/*

View File

@ -1,13 +1,13 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>RelayAngularChat</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
<head>
<meta charset="utf-8" />
<title>RelayAngularChat</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@ -1,14 +1,18 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import "zone.js/testing";
import { getTestBed } from "@angular/core/testing";
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
platformBrowserDynamicTesting,
} from "@angular/platform-browser-dynamic/testing";
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
context(
path: string,
deep?: boolean,
filter?: RegExp
): {
<T>(id: string): T;
keys(): string[];
};
@ -17,10 +21,10 @@ declare const require: {
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting(),
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
const context = require.context("./", true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

View File

@ -5,10 +5,6 @@
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
],
"include": [
"src/**/*.d.ts"
]
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"]
}

View File

@ -18,11 +18,8 @@
"importHelpers": true,
"target": "es2020",
"module": "es2020",
"lib": [
"es2020",
"dom"
],
"allowSyntheticDefaultImports": true,
"lib": ["es2020", "dom"],
"allowSyntheticDefaultImports": true
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,

View File

@ -3,15 +3,8 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
"types": ["jasmine"]
},
"files": [
"src/test.ts",
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
"files": ["src/test.ts"],
"include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

View File

@ -1,75 +1,85 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'/>
<meta content='width=device-width, initial-scale=1.0' name='viewport'/>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>JS-Waku Chat</title>
</head>
</head>
<body>
<body>
<div><h1>Waku Node Status</h1></div>
<div id="status"></div>
<div><h1>Waku Node Status</h1></div>
<div id='status'></div>
<label for="textInput">Message text</label>
<input
disabled
id="textInput"
placeholder="Type your message here"
type="text"
/>
<button disabled id="sendButton" type="button">
Send Message using Relay
</button>
<label for='textInput'>Message text</label>
<input disabled id='textInput' placeholder='Type your message here' type='text'>
<button disabled id='sendButton' type='button'>Send Message using Relay</button>
<div><h1>Messages</h1></div>
<div id="messages"></div>
<div><h1>Messages</h1></div>
<div id='messages'></div>
<script type="module">
/**
* Demonstrate usage of js-waku in the browser. Use relay, gossip sub protocol to send and receive messages.
* Recommended payload is protobuf. Using simple utf-8 string for demo purposes only.
*/
import {
bytesToUtf8,
utf8ToBytes,
} from "https://unpkg.com/@waku/byte-utils@0.0.2/bundle/index.js";
import { createPrivacyNode } from "https://unpkg.com/@waku/create@0.0.4/bundle/index.js";
import { waitForRemotePeer } from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/wait_for_remote_peer.js";
import {
DecoderV0,
EncoderV0,
} from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/waku_message/version_0.js";
<script type='module'>
/**
* Demonstrate usage of js-waku in the browser. Use relay, gossip sub protocol to send and receive messages.
* Recommended payload is protobuf. Using simple utf-8 string for demo purposes only.
*/
const statusDiv = document.getElementById("status");
const messagesDiv = document.getElementById("messages");
const textInput = document.getElementById("textInput");
const sendButton = document.getElementById("sendButton");
import {bytesToUtf8, utf8ToBytes} from 'https://unpkg.com/@waku/byte-utils@0.0.2/bundle/index.js';
import {createPrivacyNode} from 'https://unpkg.com/@waku/create@0.0.4/bundle/index.js'
import {waitForRemotePeer} from 'https://unpkg.com/@waku/core@0.0.6/bundle/lib/wait_for_remote_peer.js'
import {DecoderV0, EncoderV0} from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/waku_message/version_0.js";
// Every Waku Message has a content topic that categorizes it.
// It is always encoded in clear text.
// Recommendation: `/dapp-name/version/functionality/codec`
// We recommend to use protobuf as codec (`proto`), this demo uses utf-8
// for simplicity's sake.
const contentTopic = "/js-waku-examples/1/chat/utf8";
const statusDiv = document.getElementById('status');
const messagesDiv = document.getElementById('messages');
const textInput = document.getElementById('textInput');
const sendButton = document.getElementById('sendButton');
// Prepare encoder and decoder, `V0` for clear text messages.
// Every Waku Message has a content topic that categorizes it.
// It is always encoded in clear text.
// Recommendation: `/dapp-name/version/functionality/codec`
// We recommend to use protobuf as codec (`proto`), this demo uses utf-8
// for simplicity's sake.
const contentTopic = '/js-waku-examples/1/chat/utf8';
const encoder = new EncoderV0(contentTopic);
const decoder = new DecoderV0(contentTopic);
// Prepare encoder and decoder, `V0` for clear text messages.
const encoder = new EncoderV0(contentTopic);
const decoder = new DecoderV0(contentTopic);
try {
statusDiv.innerHTML = '<p>Starting</p>';
try {
statusDiv.innerHTML = "<p>Starting</p>";
// Create and starts a Waku node.
// `default: true` bootstraps by connecting to pre-defined/hardcoded Waku nodes.
// We are currently working on migrating this method to DNS Discovery.
//
// https://js.waku.org/functions/lib_create_waku.createPrivacyNode.html
const waku = await createPrivacyNode({defaultBootstrap: true});
const waku = await createPrivacyNode({ defaultBootstrap: true });
await waku.start();
// Add a hook to process all incoming messages on a specified content topic.
//
// https://js.waku.org/classes/index.waku_relay.WakuRelay.html#addObserver
waku.relay.addObserver(decoder, (message) => {
waku.relay.addObserver(
decoder,
(message) => {
// Checks there is a payload on the message.
// Waku Message is encoded in protobuf, in proto v3 fields are always optional.
//
// https://js.waku.org/interfaces/index.proto_message.WakuMessage-1.html#payload
if (!message.payload)
return;
if (!message.payload) return;
// Helper method to decode the payload to utf-8. A production dApp should
// use `wakuMessage.payload` (Uint8Array) which enables encoding a data
@ -77,10 +87,13 @@
//
// https://js.waku.org/functions/index.utils.bytesToUtf8.html
const text = bytesToUtf8(message.payload);
messagesDiv.innerHTML = `<p>${text}</p><br />` + messagesDiv.innerHTML;
}, [contentTopic]);
messagesDiv.innerHTML =
`<p>${text}</p><br />` + messagesDiv.innerHTML;
},
[contentTopic]
);
statusDiv.innerHTML = '<p>Connecting to a peer</p>';
statusDiv.innerHTML = "<p>Connecting to a peer</p>";
// Best effort method that waits for the Waku node to be connected to remote
// waku nodes (peers) and for appropriate handshakes to be done.
@ -92,24 +105,22 @@
// function that sends the text input over Waku Relay, the gossipsub
// protocol.
sendButton.onclick = async () => {
const payload = utf8ToBytes(textInput.value)
await waku.relay.send(encoder, {payload});
console.log('Message sent!');
const payload = utf8ToBytes(textInput.value);
await waku.relay.send(encoder, { payload });
console.log("Message sent!");
// Reset the text input.
textInput.value = null;
// Reset the text input.
textInput.value = null;
};
// Ready to send & receive messages, enable text input.
textInput.disabled = false;
sendButton.disabled = false;
statusDiv.innerHTML = '<p>Ready!</p>';
} catch (e) {
statusDiv.innerHTML = 'Failed to start application';
statusDiv.innerHTML = "<p>Ready!</p>";
} catch (e) {
statusDiv.innerHTML = "Failed to start application";
console.log(e);
}
</script>
</body>
}
</script>
</body>
</html>

View File

@ -1,26 +1,28 @@
const {getLoaders, loaderByName} = require("@craco/craco");
const { getLoaders, loaderByName } = require("@craco/craco");
module.exports = {
webpack: {
configure: (webpackConfig) => {
const {hasFoundAny, matches} = getLoaders(webpackConfig, loaderByName("babel-loader"));
webpack: {
configure: (webpackConfig) => {
const { hasFoundAny, matches } = getLoaders(
webpackConfig,
loaderByName("babel-loader")
);
if (hasFoundAny) {
matches.forEach(c => {
// Modify test to include cjs for @chainsafe/libp2p-gossipsub rpc module
if (c.loader.test.toString().includes("mjs")) {
// If your project uses typescript then do not forget to include `ts`/`tsx`
if (c.loader.test.toString().includes('jsx')) {
c.loader.test = /\.(js|cjs|mjs|jsx)$/
} else {
c.loader.test = /\.(js|cjs|mjs)$/
}
}
});
if (hasFoundAny) {
matches.forEach((c) => {
// Modify test to include cjs for @chainsafe/libp2p-gossipsub rpc module
if (c.loader.test.toString().includes("mjs")) {
// If your project uses typescript then do not forget to include `ts`/`tsx`
if (c.loader.test.toString().includes("jsx")) {
c.loader.test = /\.(js|cjs|mjs|jsx)$/;
} else {
c.loader.test = /\.(js|cjs|mjs)$/;
}
}
});
}
return webpackConfig;
}
}
}
return webpackConfig;
},
},
};

View File

@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react';
import App from './App';
import { render, screen } from "@testing-library/react";
import App from "./App";
test('renders learn react link', () => {
test("renders learn react link", () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();

View File

@ -1,13 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

View File

@ -1,9 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById('root'));
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />

View File

@ -2,4 +2,4 @@
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import "@testing-library/jest-dom";

View File

@ -83,6 +83,7 @@
<div class="row rcenter">
<h4>Key</h4>
<code class="value" id="key">none</code>
</div>
<div class="row rcenter">
<h4>Commitment</h4>
@ -203,6 +204,7 @@
node,
nodeConnected,
rlnInstance;
const allMemberships = [];
let retrievedRLNEvents = false;
const rlnInstancePromise = create();
@ -252,6 +254,7 @@
);
importManually.disabled = !(
membershipIdInput.value &&
identityKeyInput.value &&
commitmentKeyInput.value
@ -287,6 +290,7 @@
commitmentKeyInput.onchange = updateFields;
importManually.onclick = () => {
const idKey = utils.hexToBytes(identityKeyInput.value);
const idCommitment = utils.hexToBytes(commitmentKeyInput.value);
membershipKey = new MembershipKey(idKey, idCommitment);
@ -345,6 +349,7 @@
const handleMembership = (pubkey, index) => {
try {
allMemberships.push({ pubkey, index });
const idCommitment = ethers.utils.zeroPad(
ethers.utils.arrayify(pubkey),
32
@ -381,6 +386,7 @@
checkChain(network.chainId);
importFromWalletButton.disabled = false;
} catch (e) {
console.log("No web3 provider available", e);
}

View File

@ -1,62 +1,65 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'/>
<meta content='width=device-width, initial-scale=1.0' name='viewport'/>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>JS-Waku store script tag example</title>
</head>
</head>
<body>
<body>
<div><h1>Timestamp of the latest message seen in store</h1></div>
<div id="timestamp"></div>
<div><h1>Timestamp of the latest message seen in store</h1></div>
<div id='timestamp'></div>
<script type="module">
import {
defaultLibp2p,
defaultPeerDiscovery,
} from "https://unpkg.com/@waku/create@0.0.4/bundle/index.js";
import { waitForRemotePeer } from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/wait_for_remote_peer.js";
import {
wakuStore,
WakuNode,
} from "https://unpkg.com/@waku/core@0.0.6/bundle/index.js";
import { DecoderV0 } from "https://unpkg.com/@waku/core@0.0.6/bundle/lib/waku_message/version_0.js";
<script type='module'>
import {defaultLibp2p, defaultPeerDiscovery} from 'https://unpkg.com/@waku/create@0.0.4/bundle/index.js'
import {waitForRemotePeer} from 'https://unpkg.com/@waku/core@0.0.6/bundle/lib/wait_for_remote_peer.js'
import {wakuStore, WakuNode} from 'https://unpkg.com/@waku/core@0.0.6/bundle/index.js'
import {DecoderV0} from 'https://unpkg.com/@waku/core@0.0.6/bundle/lib/waku_message/version_0.js'
/**
* This example demonstrates how to use the js-waku minified bundle
* available on unpkg.com.
*
* It is a simple script that uses Waku Store to retrieve ping relay messages
* and displays the timestamp of the most recent ping relay message.
*/
const timestampDiv = document.getElementById("timestamp");
/**
* This example demonstrates how to use the js-waku minified bundle
* available on unpkg.com.
*
* It is a simple script that uses Waku Store to retrieve ping relay messages
* and displays the timestamp of the most recent ping relay message.
*/
const timestampDiv = document.getElementById('timestamp');
timestampDiv.innerHTML = "<p>Creating waku.</p>";
timestampDiv.innerHTML = '<p>Creating waku.</p>';
const libp2p = await defaultLibp2p(undefined, {
peerDiscovery: [defaultPeerDiscovery()],
});
const store = wakuStore();
const node = new WakuNode({}, libp2p, store);
const libp2p = await defaultLibp2p(
undefined,
{peerDiscovery: [defaultPeerDiscovery()]},
);
const store = wakuStore();
const node = new WakuNode({}, libp2p, store,);
timestampDiv.innerHTML = "<p>Starting waku.</p>";
await node.start();
timestampDiv.innerHTML = '<p>Starting waku.</p>';
await node.start();
timestampDiv.innerHTML = "<p>Connecting to a peer.</p>";
await waitForRemotePeer(node, ["store"]);
timestampDiv.innerHTML = '<p>Connecting to a peer.</p>';
await waitForRemotePeer(node, ["store"]);
timestampDiv.innerHTML = '<p>Retrieving messages.</p>';
const callback = (wakuMessage) => {
timestampDiv.innerHTML = "<p>Retrieving messages.</p>";
const callback = (wakuMessage) => {
// When `backward` direction is passed, first message is the most recent
timestampDiv.innerHTML = wakuMessage.timestamp;
// When returning true, `queryHistory` stops retrieving pages
// In our case, we only want one message, hence one page.
return true;
};
await node.store
.queryOrderedCallback([new DecoderV0("/relay-ping/1/ping/null")],
callback,
{pageDirection: 'backward'});
</script>
</body>
};
await node.store.queryOrderedCallback(
[new DecoderV0("/relay-ping/1/ping/null")],
callback,
{ pageDirection: "backward" }
);
</script>
</body>
</html>

View File

@ -1,9 +1,9 @@
import * as React from "react";
import protobuf from "protobufjs";
import {createLightNode} from "@waku/create";
import {waitForRemotePeer} from "@waku/core/lib/wait_for_remote_peer";
import {DecoderV0} from "@waku/core/lib/waku_message/version_0";
import {bytesToUtf8} from "@waku/byte-utils"
import { createLightNode } from "@waku/create";
import { waitForRemotePeer } from "@waku/core/lib/wait_for_remote_peer";
import { DecoderV0 } from "@waku/core/lib/waku_message/version_0";
import { bytesToUtf8 } from "@waku/byte-utils";
const ContentTopic = "/toy-chat/2/huilong/proto";
const Decoder = new DecoderV0(ContentTopic);

View File

@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react';
import App from './App';
import { render, screen } from "@testing-library/react";
import App from "./App";
test('renders learn react link', () => {
test("renders learn react link", () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();

View File

@ -1,13 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

View File

@ -2,4 +2,4 @@
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import "@testing-library/jest-dom";

View File

@ -4,11 +4,11 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<meta
name="description"
content="Chat app powered by js-waku"
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<meta name="description" content="Chat app powered by js-waku" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/

View File

@ -2,15 +2,15 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}
@ -25,6 +25,6 @@ code {
display: table;
}
.chat-room{
.chat-room {
margin: 2px;
}