JS-Waku docs (#82)

* add js-waku outline

* add js-waku quickstart

* add waku-create-app guide

* add lightpush filter guide

* add complete relay guide

* initial feedback + add emitSelf

* add store guide outline

* add store query options

* update code snippets
This commit is contained in:
LordGhostX 2023-07-11 18:52:38 +01:00 committed by GitHub
parent a5b8407b9a
commit 301a4d8d22
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 718 additions and 453 deletions

View File

@ -1,282 +0,0 @@
---
title: Build a Chat App
---
# Build a Chat App
In this guide, you will learn how to receive and send messages using Waku by building an app from scratch.
If you want to learn how to add Waku to an existing app, check the [Quick Start](./quick-start) guide.
## Pre-Requisites
### 1. Set up Project
Setup a new npm package:
```shell
mkdir waku-app
cd waku-app
npm init -y
```
### 2. Set up Web Server
Use the `serve` package as a web server
```shell
npm i -D serve
```
Add a `start` script to the `package.json` file:
```json
{
"scripts": {
"start": "serve ."
}
}
```
### 3. Create Files
Finally, create empty files for your project:
```shell
touch index.html index.js
```
## Write Your App
## 1. Add HTML Elements
In `index.html`, add a button, text box and `div` for messages to have a basic chat app.
Also, import the `index.js` file.
```html title=index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Waku Chat App</title>
</head>
<body>
<label for="textInput">Message text</label>
<input id="textInput" placeholder="Type your message here" type="text"/>
<button disabled id="send" type="button">
Send message using Light Push
</button>
<br/>
<div id="messages"></div>
<script src="./index.js" type="module"></script>
</body>
</html>
```
## 2. Access HTML Elements
::: note
From now on, all changes need to be done in the `index.js` file.
:::
Initialize variables to easily modify the HTML content:
```js
const sendButton = document.getElementById("send")
const messagesDiv = document.getElementById("messages")
const textInput = document.getElementById("textInput")
```
## 3. Start a Waku Node
Create and start a Waku Node:
```js
import {createLightNode} from "https://unpkg.com/@waku/create@0.0.12/bundle/index.js"
const wakuNode = await createLightNode({defaultBootstrap: true})
await wakuNode.start()
```
:::info
Setting the `defaultBootstrap` option to true allows your Waku node to connect to a set of pre-defined nodes.
:::
## 4. Wait for Connection to be Established
Your Waku node needs to connect to a remote node in order to access the network.
To wait for this, use the `waitForRemotePeer` function:
```js
import * as waku from "https://unpkg.com/@waku/core@0.0.16/bundle/index.js"
await waku.waitForRemotePeer(wakuNode)
```
## 5. Define a Content Topic
The `contentTopic` is a metadata `string` used for categorizing messages on the Waku Network.
Depending on your use case, you can create one or more new `contentTopic`(s).
Refer to our [How to Choose a Content Topic](/) guide more details.
For this guide, we'll use `/chat-app-guide/1/message/utf8`.
Note that our payload will be encoded using `utf-8`.
We recommended using Protobuf for production purposes.
```js
const contentTopic = `/chat-app-guide/1/message/utf8`
```
## 6. Render Incoming Messages
Let's store incoming messages in an array and create a function to render them in the `messages` div:
```js
const updateMessages = (msgs, div) => {
div.innerHTML = "<ul>"
msgs.forEach((msg) => (div.innerHTML += `<li>${msg}</li>`))
div.innerHTML += "</ul>"
}
const messages = []
```
## 7. Create a Decoder
Waku supports various encryption protocols.
A decoder allows you to specify the content topic to use and how to decrypt messages.
For the chosen content topic, create a plain text decoder (without encryption):
```js
const decoder = waku.createDecoder(contentTopic)
```
## 8. Listen for Incoming Messages
Messages sent over the network are `Waku Message`s,
as defined in the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#wire-format) RFC.
Messages returned by the plain text decoder implement the [`DecodedMessage`](https://js.waku.org/classes/_waku_core.DecodedMessage.html) interface.
For now, we will just use the `payload` field.
It is a byte array field that can be used to encode any data.
We will store messages as a `utf-8` string.
Listen to messages using the decoder and add them to the `messages` div upon reception:
```ts
import * as utils from "https://unpkg.com/@waku/utils@0.0.4/bundle/bytes.js"
wakuNode.filter.subscribe([decoder], (message) => {
const str = utils.bytesToUtf8(message.payload)
messages.push(str)
updateMessages(messages, messagesDiv);
})
```
## 9. Send Messages
Finally, create a plain text encoder and set up the `send` button to send messages.
Users will be able to enter the message using the `textInput` div.
Once done, we can enable the `send` button.
```ts
const encoder = waku.createEncoder({contentTopic})
sendButton.onclick = async () => {
const text = textInput.value
await wakuNode.lightPush.send(encoder, {
payload: utils.utf8ToBytes(text),
});
textInput.value = null
};
sendButton.disabled = false
```
### 10. Run the App
You can now start a local web server to run the app:
```shell
npm start
```
Click on the link in the console (http://localhost:3000/) and send a message!
You can open your app in several tabs to see messages being sent around.
## Conclusion
Congratulations on building your first Waku chat app. You can find the complete files below:
```html title=index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>JS-Waku Quick Start App</title>
</head>
<body>
<label for="textInput">Message text</label>
<input id="textInput" placeholder="Type your message here" type="text"/>
<button disabled id="send" type="button">
Send message using Light Push
</button>
<br/>
<div id="messages"></div>
<script src="./index.js" type="module"></script>
</body>
</html>
```
```js title=index.js
import {createLightNode} from "https://unpkg.com/@waku/create@0.0.12/bundle/index.js"
import * as waku from "https://unpkg.com/@waku/core@0.0.16/bundle/index.js"
import * as utils from "https://unpkg.com/@waku/utils@0.0.4/bundle/bytes.js"
const sendButton = document.getElementById("send")
const messagesDiv = document.getElementById("messages")
const textInput = document.getElementById("textInput")
const wakuNode = await createLightNode({defaultBootstrap: true})
await wakuNode.start()
await waku.waitForRemotePeer(wakuNode)
const contentTopic = `/chat-app-guide/1/message/utf8`
const updateMessages = (msgs, div) => {
div.innerHTML = "<ul>"
msgs.forEach((msg) => (div.innerHTML += `<li>${msg}</li>`))
div.innerHTML += "</ul>"
}
const messages = []
const decoder = waku.createDecoder(contentTopic)
wakuNode.filter.subscribe([decoder], (message) => {
console.log("message received", message)
const str = utils.bytesToUtf8(message.payload)
messages.push(str)
updateMessages(messages, messagesDiv);
})
const encoder = waku.createEncoder({contentTopic})
sendButton.onclick = async () => {
const text = textInput.value
await wakuNode.lightPush.send(encoder, {
payload: utils.utf8ToBytes(text),
})
textInput.value = null
}
sendButton.disabled = false
```

View File

@ -1,40 +0,0 @@
---
title: Introduction
slug: /clients/js-waku
---
# JS-Waku Documentation
[JS-Waku](https://github.com/waku-org/js-waku) is the TypeScript implementation of the Waku protocol,
specifically designed for the browser environment.
This powerful, easy-to-use library enables you to integrate Waku into your web applications seamlessly.
:::info
If you wish to use Waku with a NodeJS application, you can either:
- Use [nwaku](https://github.com/status-im/nwaku)'s [JSON RPC API](https://rfc.vac.dev/spec/16/)
- Or, attempt to use go-waku's [c-bindings](https://github.com/waku-org/go-waku/tree/master/examples/c-bindings) in NodeJS
:::
To get started, the [Quick Start](/) guide offers a simple way to integrate Waku into your web app.
For a more comprehensive tutorial, follow the [Build a Chat App](/) guide,
which demonstrates how to create a chat app from scratch.
Explore the [js-waku-examples repository](https://github.com/waku-org/js-waku-examples) to find various working Proof-of-Concepts that showcase how to use JS-Waku effectively.
You can also interact with these examples live:
- [web-chat](https://examples.waku.org/web-chat): A simple public chat.
- [eth-pm](https://examples.waku.org/eth-pm): End-to-end encrypted private messages.
- [rln-js](https://examples.waku.org/rln-js): Demonstration of [RLN](https://rfc.vac.dev/spec/32/),
an economic spam protection protocol that rate limit using zero-knowledge for privacy preserving purposes.
To gain a deeper understanding of Waku, visit the [overview documentation](/).
If you are interested in learning how Waku works under the hood, check out the specs at [rfc.vac.dev](https://rfc.vac.dev/).
## Bugs, Questions & Support
If you encounter any bug or would like to propose new features, feel free to [open an issue](https://github.com/waku-org/js-waku/issues/new/).
For general discussion, get help or latest news,
join **#js-waku** on [Vac Discord](https://discord.gg/Nrac59MfSX) or the [Waku Telegram Group](https://t.me/waku_org).

View File

@ -1,115 +0,0 @@
---
title: Quick Start
date: 2021-12-09T14:00:00+01:00
weight: 20
---
# Quick Start
In this guide, you will learn how to integrate Waku into an **existing** JavaScript project.
If you're looking to build a Waku app from scratch, check out our [Build a Chat App](./build-chat-app) guide.
## 1. Install Waku Libraries
To begin, install the required Waku libraries with the following command:
```shell
npm i @waku/core @waku/create @waku/utils
```
## 2. Start a Waku Node
Next, create and start a Waku Node:
```js
import {createLightNode} from "@waku/create"
const waku = await createLightNode({defaultBootstrap: true})
await waku.start()
```
:::info
Setting the `defaultBootstrap` option to true allows your Waku node to connect to a set of pre-defined nodes.
:::
## 3. Wait for Connection to be Established
Your Waku node needs to connect to a remote node in order to access the network.
To wait for this, use the `waitForRemotePeer` function:
```js
import * as waku from "@waku/core"
await waku.waitForRemotePeer(wakuNode)
```
## 4. Define a Content Topic
The `contentTopic` is a metadata `string` used for categorizing messages on the Waku Network.
Depending on your use case, you can create one or more new `contentTopic`(s).
Refer to our [How to Choose a Content Topic](/) guide more details.
For this guide, we'll use `/quick-start/1/message/utf8`.
Note that our payload will be encoded using `utf-8`.
We recommended using Protobuf for production purposes.
```js
const contentTopic = `/quick-start/1/message/utf8`
```
## 5. Create a Decoder
Waku supports various encryption protocols.
A decoder allows you to specify the content topic to use and how to decrypt messages.
For the chosen content topic, create a plain text decoder (without encryption):
```js
const decoder = waku.createDecoder(contentTopic)
```
## 6. Listen for Incoming Messages
Messages sent over the network are `Waku Message`s,
as defined in the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#wire-format) RFC.
Messages returned by the plain text decoder implement the [`DecodedMessage`](https://js.waku.org/classes/_waku_core.DecodedMessage.html) interface.
For now, we will just use the `payload` field.
It is a byte array field that can be used to encode any data.
We will store messages as a `utf-8` string.
To listen for messages using the decoder, use the following code:
```js
wakuNode.filter.subscribe([decoder], (message) => {
const str = utils.bytesToUtf8(message.payload)
// str is a string, render it in your app as desired
})
```
## 7. Send Messages
Finally, create a `sendMessage` function that sends messages over Waku:
```js
import * as utils from "@waku/utils"
const encoder = waku.createEncoder(contentTopic)
const sendMessage = async (textMsg) => {
await wakuNode.lightPush.push(encoder, {
payload: utils.utf8ToBytes(textMsg),
});
};
```
Now, you can use the `sendMessage` function in your app to send messages.
## Conclusion
Congratulations! You've successfully added decentralized communication features to your app.
Continue learning by exploring how to [build a chat app](./build-chat-app) from scratch using Waku.

View File

@ -0,0 +1,55 @@
---
title: JavaScript Waku SDK
---
The [JavaScript Waku SDK](https://github.com/waku-org/js-waku) (`js-waku`) provides a TypeScript implementation of the [Waku protocol](/) designed for web browser environments. Developers can seamlessly integrate Waku functionalities into web applications, enabling efficient communication and collaboration among users using the `js-waku` SDK.
## Installation
Install the `js-waku` SDK using your preferred package manager:
```mdx-code-block
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
```
<Tabs>
<TabItem value="npm" label="npm">
```shell
npm install @waku/sdk
```
</TabItem>
<TabItem value="yarn" label="Yarn">
```shell
yarn add @waku/sdk
```
</TabItem>
</Tabs>
You can also use the `js-waku` SDK via a CDN without installing it on your system:
```js
import * as waku from "https://unpkg.com/@waku/sdk@latest/bundle/index.js";
```
## Getting Started
Check out the [quick start](/guides/js-waku/quick-start) guide and comprehensive tutorials to learn how to build applications with `js-waku`.
| Guide | Description |
| - | - |
| [Quick Start](/guides/js-waku/quick-start) | Quickly familiarize yourself with `js-waku` by setting up a Waku node and sending messages using the [Relay](/overview/concepts/protocols#relay) protocol |
| [Send and Receive Messages Using Relay](/guides/js-waku/relay-send-receive) | Learn how to set up a Waku node for sending and receiving messages using the [Relay](/overview/concepts/protocols#relay) protocol |
| [Send and Receive Messages Using Light Push and Filter](/guides/js-waku/light-send-receive) | Learn how to send and receive messages on light nodes using the [Light Push](/overview/concepts/protocols#light-push) and [Filter](/overview/concepts/protocols#filter) protocols |
| [Retrieve Messages Using Store](/guides/js-waku/store-retrieve-messages) | Learn how to retrieve and filter historical messages on light nodes using the [Store](/overview/concepts/protocols#store) protocol |
| [Bootstrap DApps Using @waku/create-app](/guides/js-waku/waku-create-app) | Learn how to use the [@waku/create-app](https://www.npmjs.com/package/@waku/create-app) package to bootstrap your next `js-waku` project from various example templates |
## Get Help and Report Issues
To engage in general discussions, seek assistance, or stay updated with the latest news, visit the `#support` and `#js-waku-contribute` channels on the [Waku Discord](https://discord.waku.org).
If you discover bugs or want to suggest new features, do not hesitate to [open an issue](https://github.com/waku-org/js-waku/issues/new/) in the [js-waku repository](https://github.com/waku-org/js-waku). Your feedback and contributions are highly valued and will help improve the `js-waku` SDK.

View File

@ -0,0 +1,97 @@
---
title: Send and Receive Messages Using Light Push and Filter
---
This guide provides detailed steps to create a light node, send messages using the [Light Push protocol](/overview/concepts/protocols#light-push), and receive messages using the [Filter protocol](/overview/concepts/protocols#filter).
## Create a Waku Node
Set up a Waku node by creating a light node, connecting to network peers with `Light Push` and `Filter` enabled, choosing a [content topic](/overview/concepts/content-topics), and creating an `encoder` and `decoder` for [message encryption](https://rfc.vac.dev/spec/26/):
```js
import {
createLightNode,
waitForRemotePeer,
Protocols,
createEncoder,
createDecoder
} from "@waku/sdk";
// Create and start a light node
const node = await createLightNode({ defaultBootstrap: true });
await node.start();
// Wait for a successful peer connection
await waitForRemotePeer(node, [
Protocols.LightPush,
Protocols.Filter,
]);
// Choose a content topic
const contentTopic = "/light-guide/1/message/proto";
// Create a message encoder and decoder
const encoder = createEncoder({ contentTopic });
const decoder = createDecoder(contentTopic);
```
## Create a Message Structure
Create your application's message structure using [Protobuf's valid message](https://github.com/protobufjs/protobuf.js#usage) fields:
```js
import protobuf from "protobufjs";
// Create a message structure using Protobuf
const ChatMessage = new protobuf.Type("ChatMessage")
.add(new protobuf.Field("timestamp", 1, "uint64"))
.add(new protobuf.Field("sender", 2, "string"))
.add(new protobuf.Field("message", 3, "string"));
```
:::info
Please refer to the [Protobuf installation](/guides/js-waku/quick-start#create-a-message-structure) guide for steps on adding the `protobufjs` package to your project.
:::
## Send Messages Using Light Push
To send messages over the Waku Network using the `Light Push` protocol, create a new message object and use the `lightPush.send()` function:
```js
// Create a new message object
const protoMessage = ChatMessage.create({
timestamp: Date.now(),
sender: "Alice",
message: "Hello, World!",
});
// Serialize the message using Protobuf
const serializedMessage = ChatMessage.encode(protoMessage).finish();
// Send the message using Light Push
await node.lightPush.send(encoder, {
payload: serializedMessage,
});
```
## Receive Messages Using Filter
Use the `filter.subscribe()` function to listen for incoming messages on a specific content topic:
```js
// Subscribe to content topics and display new messages
const unsubscribe = await node.filter.subscribe([decoder], (wakuMessage) => {
// Check if there is a payload on the message
if (!wakuMessage.payload) return;
// Render the messageObj as desired in your application
const messageObj = ChatMessage.decode(wakuMessage.payload);
console.log(messageObj);
});
// Use the unsubscribe() function to stop receiving messages
// await unsubscribe();
```
:::tip Congratulations!
You have successfully sent and received messages over the Waku Network using the `Light Push` and `Filter` protocols.
:::

View File

@ -0,0 +1,144 @@
---
title: Quick Start
---
This guide provides quick steps to start using the `js-waku` SDK by setting up a Waku node and sending messages using the [Relay protocol](/overview/concepts/protocols#relay). Please refer to the [installation guide](/guides/js-waku/#installation) for steps on adding `js-waku` to your project.
## Create a Relay Node
Use the `createRelayNode()` function to create a relay node and interact with the Waku Network:
```js
import { createRelayNode } from "@waku/sdk";
// Create and start a relay node
const node = await createRelayNode({ defaultBootstrap: true });
await node.start();
// Use the stop() function to stop a running node
// await node.stop();
```
:::info
The `defaultBootstrap` option bootstraps your node using [pre-defined Waku nodes](/overview/concepts/static-peers).
:::
## Connect to Remote Peers
Use the `waitForRemotePeer()` function to wait for the node to connect with peers on the Waku Network:
```js
import { waitForRemotePeer } from "@waku/sdk";
// Wait for a successful peer connection
await waitForRemotePeer(node);
```
The `protocols` option allows you to specify the [protocols](/overview/concepts/protocols) that the remote peers should have enabled:
```js
import { waitForRemotePeer, Protocols } from "@waku/sdk";
// Wait for peer connections with specific protocols
await waitForRemotePeer(node, [
Protocols.Relay,
Protocols.Store,
Protocols.LightPush,
Protocols.Filter,
]);
```
## Choose a Content Topic
[Choose a content topic](/overview/concepts/content-topics) for your application and create an `encoder` for [message encryption](https://rfc.vac.dev/spec/26/):
```js
import { createEncoder } from "@waku/sdk";
// Choose a content topic
const contentTopic = "/quick-start/1/message/proto";
// Create a message encoder
const encoder = createEncoder({ contentTopic });
```
## Create a Message Structure
Create a message structure for your application using [Protocol Buffers](https://protobuf.dev/) (`proto`) for the following reasons:
1. **Consistency:** Ensures uniform message format for easy parsing and processing.
2. **Interoperability:** Facilitates effective communication between different parts of your application.
3. **Compatibility:** Allows smooth communication between older and newer app versions.
To get started, install the `protobufjs` package using your preferred package manager:
```mdx-code-block
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
```
<Tabs>
<TabItem value="npm" label="npm">
```shell
npm install protobufjs
```
</TabItem>
<TabItem value="yarn" label="Yarn">
```shell
yarn add protobufjs
```
</TabItem>
</Tabs>
You can also use the `protobufjs` package via a CDN without installing it on your system:
```js
// Import the CDN
import "https://cdn.jsdelivr.net/npm/protobufjs@latest/dist/protobuf.min.js";
```
```html
<!-- Or include the protobufjs script -->
<script src="https://cdn.jsdelivr.net/npm/protobufjs@latest/dist/protobuf.min.js"></script>
```
Next, create the message structure using [Protobuf's valid message](https://github.com/protobufjs/protobuf.js#usage) fields:
```js
import protobuf from "protobufjs";
// Create a message structure using Protobuf
const ChatMessage = new protobuf.Type("ChatMessage")
.add(new protobuf.Field("timestamp", 1, "uint64"))
.add(new protobuf.Field("sender", 2, "string"))
.add(new protobuf.Field("message", 3, "string"));
```
## Send Messages Using Relay
To send messages using the `Relay` protocol, create a new message object and use the `relay.send()` function:
```js
// Create a new message object
const protoMessage = ChatMessage.create({
timestamp: Date.now(),
sender: "Alice",
message: "Hello, World!",
});
// Serialize the message using Protobuf
const serializedMessage = ChatMessage.encode(protoMessage).finish();
// Send the message using Relay
await node.relay.send(encoder, {
payload: serializedMessage,
});
```
:::tip Congratulations!
You have successfully added decentralized communication features to your application using `js-waku`.
:::

View File

@ -0,0 +1,100 @@
---
title: Send and Receive Messages Using Relay
---
This guide provides detailed steps to set up a Waku node for sending and receiving messages using the [Relay protocol](/overview/concepts/protocols#relay).
## Create a Waku Node
Set up a Waku node by creating a relay node, connecting to network peers, choosing a [content topic](/overview/concepts/content-topics), and creating an `encoder` and `decoder` for [message encryption](https://rfc.vac.dev/spec/26/):
```js
import {
createRelayNode,
waitForRemotePeer,
createEncoder,
createDecoder
} from "@waku/sdk";
// Create and start a relay node
const node = await createRelayNode({
defaultBootstrap: true, // bootstraps using pre-defined nodes
emitSelf: true, // emits sent message events to itself
});
await node.start();
// Wait for a successful peer connection
await waitForRemotePeer(node);
// Choose a content topic
const contentTopic = "/relay-guide/1/message/proto";
// Create a message encoder and decoder
const encoder = createEncoder({ contentTopic });
const decoder = createDecoder(contentTopic);
```
:::info
The `emitSelf` option emits sent message events to itself and invokes the node's subscribers.
:::
## Create a Message Structure
Create your application's message structure using [Protobuf's valid message](https://github.com/protobufjs/protobuf.js#usage) fields:
```js
import protobuf from "protobufjs";
// Create a message structure using Protobuf
const ChatMessage = new protobuf.Type("ChatMessage")
.add(new protobuf.Field("timestamp", 1, "uint64"))
.add(new protobuf.Field("sender", 2, "string"))
.add(new protobuf.Field("message", 3, "string"));
```
:::info
Please refer to the [Protobuf installation](/guides/js-waku/quick-start#create-a-message-structure) guide for steps on adding the `protobufjs` package to your project.
:::
## Send Messages Using Relay
To send messages using the `Relay` protocol, create a new message object and use the `relay.send()` function:
```js
// Create a new message object
const protoMessage = ChatMessage.create({
timestamp: Date.now(),
sender: "Alice",
message: "Hello, World!",
});
// Serialize the message using Protobuf
const serializedMessage = ChatMessage.encode(protoMessage).finish();
// Send the message using Relay
await node.relay.send(encoder, {
payload: serializedMessage,
});
```
## Receive Messages Using Relay
Use the `relay.subscribe()` function to listen for incoming messages on a specific content topic:
```js
// Subscribe to content topics and display new messages
const unsubscribe = await node.relay.subscribe([decoder], (wakuMessage) => {
// Check if there is a payload on the message
if (!wakuMessage.payload) return;
// Render the messageObj as desired in your application
const messageObj = ChatMessage.decode(wakuMessage.payload);
console.log(messageObj);
});
// Use the unsubscribe() function to stop receiving messages
// await unsubscribe();
```
:::tip Congratulations!
You have successfully sent and received messages over the Waku Network using the `Relay` protocol.
:::

View File

@ -0,0 +1,219 @@
---
title: Retrieve Messages Using Store
---
This guide provides detailed steps to create a light node for retrieving and filtering historical messages using the [Store protocol](/overview/concepts/protocols#store).
## Create a Light Node
Use the `createLightNode()` function to create a light node and interact with the Waku Network:
```js
import { createLightNode } from "@waku/sdk";
// Create and start a light node
const node = await createLightNode({ defaultBootstrap: true });
await node.start();
```
## Connect to Store Peers
Use the `waitForRemotePeer()` function to wait for the node to connect with store peers:
```js
import { waitForRemotePeer, Protocols } from "@waku/sdk";
// Wait for a successful peer connection
await waitForRemotePeer(node, [Protocols.Store]);
```
## Choose a Content Topic
[Choose a content topic](/overview/concepts/content-topics) for filtering the messages to retrieve and create a `decoder` for [message decryption](https://rfc.vac.dev/spec/26/):
```js
import { createDecoder } from "@waku/sdk";
// Choose a content topic
const contentTopic = "/store-guide/1/message/proto";
// Create a message decoder
const decoder = createDecoder(contentTopic);
```
## Retrieve Messages
`js-waku` provides the `queryOrderedCallback()` and `queryGenerator()` functions for querying `Store` nodes and retrieving historical or missed messages. The responses from `Store` nodes are paginated and require you to handle them sequentially, processing each page when received.
### `queryOrderedCallback`
The `store.queryOrderedCallback()` function provides a straightforward method for querying `Store` nodes and processing messages in chronological order through a callback function. It accepts these parameters:
- `decoders`: List of `decoders` that specify the `content topic` to query for and their [message decryption](https://rfc.vac.dev/spec/26/) methods.
- `callback`: The callback function for processing the retrieved messages.
- `options` (optional): [Query options](/guides/js-waku/store-retrieve-messages#store-query-options) to filter the retrieved messages.
```js
// Create the callback function
const callback = (wakuMessage) => {
// Render the message/payload in your application
console.log(wakuMessage);
};
// Set the query options
const queryOptions = {
pageSize: 5,
};
// Query the Store node
await node.store.queryOrderedCallback(
[decoder],
callback,
queryOptions,
);
```
### `queryGenerator`
The `store.queryGenerator()` function provides more control and flexibility over processing messages retrieved from `Store` nodes through [Async Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator). It accepts these parameters:
- `decoders`: List of `decoders` that specify the `content topic` to query for and their [message decryption](https://rfc.vac.dev/spec/26/) methods.
- `options` (optional): [Query options](/guides/js-waku/store-retrieve-messages#store-query-options) to filter the retrieved messages.
```js
// Set the query options
const queryOptions = {
pageSize: 5,
};
// Create the store query
const storeQuery = node.store.queryGenerator(
[decoder],
queryOptions,
);
// Process the messages
for await (const messagesPromises of storeQuery) {
// Fulfill all the messages promises
const messages = await Promise.all(messagesPromises);
// Render the message/payload in your application
console.log(messages);
}
```
## Store Query Options
### `pageDirection`
The `pageDirection` option specifies the direction in which pages are retrieved:
- `BACKWARD` (default): Most recent page first.
- `FORWARD`: Oldest page first.
```js
import { PageDirection } from "@waku/sdk";
// Retrieve recent messages first
const queryOptions = {
pageDirection: PageDirection.BACKWARD,
};
// Retrieve oldest messages first
const queryOptions = {
pageDirection: PageDirection.FORWARD,
};
```
:::info
The `pageDirection` option does not affect the ordering of messages within the page, as the oldest message always returns first.
:::
### `pageSize`
The `pageSize` option specifies the number of messages to be returned per page. For example, consider a query that retrieves `20` messages per page:
```js
const queryOptions = {
pageSize: 20,
};
```
### `timeFilter`
The `timeFilter` option specifies a time frame to retrieve messages from. For example, consider a query that retrieves messages from the previous week:
```js
// Get the time frame
const endTime = new Date();
const startTime = new Date();
startTime.setDate(endTime.getDate() - 7);
// Retrieve a week of messages
const queryOptions = {
timeFilter: {
startTime,
endTime,
},
};
```
:::info
If you omit the `timeFilter` option, the query will start from the beginning or end of the history, depending on the [page direction](#pagedirection).
:::
### `cursor`
The `cursor` option specifies the starting index for retrieving messages. For example, consider a query that retrieves the first `10` messages and then continues with the next `10` messages:
```js
import { waku } from "@waku/sdk";
// Create the callback function
const messages = [];
const callback = (wakuMessage) => {
messages.push(wakuMessage);
};
// Retrieve the first 10 messages
await node.store.queryOrderedCallback(
[decoder],
callback,
{
pageSize: 10,
},
);
// Create the cursor
const lastMessage = messages[messages.length - 1];
const cursor = await waku.createCursor(lastMessage);
// Retrieve the next 10 messages
// The message at the cursor index is excluded from the result
await node.store.queryOrderedCallback(
[decoder],
callback,
{
pageSize: 10,
cursor: cursor,
},
);
console.log(messages);
```
:::info
If you omit the `cursor` option, the query will start from the beginning or end of the history, depending on the [page direction](#pagedirection).
:::
### `peerId`
The `peerId` option specifies the peer to query. If omitted, a pseudo-random peer is selected from the connected `Store` peers.
```js
const queryOptions = {
peerId: "[WAKU STORE PEER ID]",
};
```
:::tip Congratulations!
You have successfully retrieved and filtered historical messages on a light node using the `Store` protocol.
:::

View File

@ -0,0 +1,56 @@
---
title: "Bootstrap DApps Using @waku/create-app"
---
This guide provides detailed steps to bootstrap your next `js-waku` project from [various example templates](https://github.com/waku-org/js-waku-examples/tree/master/examples) using the [@waku/create-app](https://www.npmjs.com/package/@waku/create-app) package.
## Usage
Initialize a new `js-waku` template using any of the following methods:
```mdx-code-block
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
```
<Tabs>
<TabItem value="npx" label="npx">
```shell
npx @waku/create-app [PROJECT DIRECTORY]
```
</TabItem>
<TabItem value="npm" label="npm">
```shell
npm init @waku/app [PROJECT DIRECTORY]
```
</TabItem>
<TabItem value="yarn" label="Yarn">
```shell
yarn create @waku/app [PROJECT DIRECTORY]
```
</TabItem>
</Tabs>
Next, select a template to initialize your app from:
![waku create app demo](/img/waku-create-app-demo.gif)
:::tip
If you have previously installed `@waku/create-app` globally, we recommend uninstalling the package to ensure that `npx` always uses the latest version.
:::
## Contributing New Templates
We welcome and appreciate the contributions of templates for the `@waku/create-app` package. To contribute a template, please follow these steps:
1. Create the template, ensuring it is user-friendly and thoroughly tested.
2. Place the template in the `examples` folder in the [js-waku-examples](https://github.com/waku-org/js-waku-examples) repository's root.
3. Commit your changes with a detailed message and push them to your forked repository.
4. Finally, submit a pull request to the [js-waku-examples](https://github.com/waku-org/js-waku-examples) repository.
5. Our team will carefully review your submission and merge it upon approval.

View File

@ -23,7 +23,7 @@ Waku is implemented in multiple SDKs, allowing it to integrate with different la
| | Description | Documentation |
| - | - | - |
| [js-waku](https://github.com/waku-org/js-waku) | JavaScript/TypeScript SDK designed for browser environments | |
| [js-waku](https://github.com/waku-org/js-waku) | JavaScript/TypeScript SDK designed for browser environments | [JavaScript Waku SDK](/guides/js-waku/) |
| [nwaku](https://github.com/waku-org/nwaku) | Nim SDK designed for integration with native Nim applications | |
| [go-waku](https://github.com/waku-org/go-waku) | Golang SDK designed for integration with Golang applications, includes C bindings for usage in C/C++, C#/Unity, Swift, and Kotlin | |
| [waku-rust-bindings](https://github.com/waku-org/waku-rust-bindings) | Rust wrapper using `go-waku` bindings designed for integration in Rust applications | |
@ -44,5 +44,5 @@ Waku provides integrations tailored for mobile applications, enabling Waku to ru
| - | - | - |
| JSON-RPC API | `JSON-RPC` API interface provided by `nwaku` and `go-waku` to interact with the Waku Network | |
| [@waku/react](https://www.npmjs.com/package/@waku/react) | React components and UI adapters designed for seamless integration with `js-waku` | |
| [@waku/create-app](https://www.npmjs.com/package/@waku/create-app) | Starter kit to bootstrap your next `js-waku` project from various example templates | |
| [nwaku-compose](https://github.com/alrevuelta/nwaku-compose) | Pre-configured Docker Compose setup for running and monitoring a `nwaku` node using Prometheus and Grafana. | [Run Nwaku with Docker Compose](/guides/nwaku/run-docker-compose) |
| [@waku/create-app](https://www.npmjs.com/package/@waku/create-app) | Starter kit to bootstrap your next `js-waku` project from various example templates | [Bootstrap DApps Using @waku/create-app](/guides/js-waku/waku-create-app) |
| [nwaku-compose](https://github.com/alrevuelta/nwaku-compose) | Pre-configured Docker Compose setup for running and monitoring a `nwaku` node using Prometheus and Grafana | [Run Nwaku with Docker Compose](/guides/nwaku/run-docker-compose) |

View File

@ -9,7 +9,7 @@ This guide provides detailed steps to build a `nwaku` node from the source code
- Nwaku is available for Linux and macOS, with experimental Windows support.
:::
## Install Dependencies
## Prerequisites
To build `nwaku`, you need the standard developer tools, including a C compiler, Make, Bash, Git, and PostgreSQL client library.

View File

@ -4,7 +4,7 @@ title: Configure Peer Discovery
This guide provides detailed steps to configure a `nwaku` node to discover and connect with peers in the Waku Network.
:::tip
:::info
You can configure a `nwaku` node to use multiple peer discovery mechanisms simultaneously.
:::
@ -18,7 +18,7 @@ You can provide static peers to a `nwaku` node during startup using the `staticn
--staticnode=[PEER MULTIADDR 2]
```
For instance, consider a `nwaku` node that connects to two static peers on the same local host (IP: `0.0.0.0`) using TCP ports `60002` and `60003`:
For example, consider a `nwaku` node that connects to two static peers on the same local host (IP: `0.0.0.0`) using TCP ports `60002` and `60003`:
```bash
./build/wakunode2 \
@ -45,7 +45,7 @@ To enable [DNS Discovery](/overview/concepts/dns-discovery) in a `nwaku` node, u
If you omit the `dns-discovery-name-server` option, `nwaku` will attempt to use the CloudFlare servers `1.1.1.1` and `1.0.0.1`.
:::
For instance, consider a `nwaku` node that enables `DNS Discovery`, connects to a DNS node list, and queries the IPs `8.8.8.8` and `8.8.4.4`:
For example, consider a `nwaku` node that enables `DNS Discovery`, connects to a DNS node list, and queries the IPs `8.8.8.8` and `8.8.4.4`:
```bash
./build/wakunode2 \
@ -69,7 +69,7 @@ To enable [Discv5](/overview/concepts/discv5) in a `nwaku` node, use the followi
--discv5-bootstrap-node=[DISCV5 ENR BOOTSTRAP ENTRY 2]
```
For instance, consider a `nwaku` node that enables `Discv5` and bootstraps its routing table using a static `ENR`:
For example, consider a `nwaku` node that enables `Discv5` and bootstraps its routing table using a static `ENR`:
```bash
./build/wakunode2 \
@ -94,7 +94,7 @@ To enable [Peer Exchange](/overview/concepts/peer-exchange) in a `nwaku` node, u
--peer-exchange-node=[PEER MULTIADDR WITH EXCHANGE ENABLED]
```
For instance, consider two `nwaku` nodes configured as a `server` (peer exchange responder node) and `client` (node using peer exchange) on the same local host (IP: `0.0.0.0`):
For example, consider two `nwaku` nodes configured as a `server` (peer exchange responder node) and `client` (node using peer exchange) on the same local host (IP: `0.0.0.0`):
```bash title="Server: Nwaku Node with Peer Exchange Enabled"
./build/wakunode2 --peer-exchange=true

View File

@ -2,7 +2,7 @@
title: Run Nwaku with Docker Compose
---
`nwaku-compose` is a ready-to-use `docker-compose` setup that runs a nwaku node and monitors it with already configured [Prometheus](https://prometheus.io/) and [Grafana](https://grafana.com/) instances.
`nwaku-compose` is a ready-to-use Docker Compose setup that runs a nwaku node and monitors it with already configured [Prometheus](https://prometheus.io/) and [Grafana](https://grafana.com/) instances.
This guide provides detailed steps to build, configure, run, and monitor a `nwaku` node with [nwaku-compose](https://github.com/alrevuelta/nwaku-compose).

View File

@ -59,7 +59,7 @@ To join the Waku Network, nodes must [bootstrap](/overview/reference/glossary#bo
| Discv5 | Enable `nwaku` to discover peers using the [Discv5](/overview/concepts/discv5) mechanism | [Configure Discv5](/guides/nwaku/configure-discovery#configure-discv5) |
| Peer Exchange | Enable [Peer Exchange](/overview/concepts/peer-exchange) protocol for light nodes to request peers from your `nwaku` node | [Configure Peer Exchange](/guides/nwaku/configure-discovery#configure-peer-exchange) |
:::tip
:::info
You can configure a `nwaku` node to use multiple peer discovery mechanisms simultaneously.
:::

View File

@ -13,9 +13,9 @@ Here is the recommended format for content topics:
- `application-name`: This is the unique name of your decentralized application (dApp) to prevent conflicts with other dApps.
- `version`: Typically starting at `1`, this field helps track breaking changes in your messages.
- `content-topic-name`: The specific name of the content topic used for filtering.
- `encoding`: The message serialization/encoding format, with [Protocol Buffers](https://protobuf.dev/) (`proto`) being the recommended choice.
- `encoding`: The message encoding or serialization format, with [Protocol Buffers](https://protobuf.dev/) (`proto`) being the recommended choice.
For instance, if your dApp is called `SuperCrypto` and it allows users to receive notifications and send private messages, you can consider using the following content topics:
For example, if your dApp is called `SuperCrypto` and it allows users to receive notifications and send private messages, you can consider using the following content topics:
- `/supercrypto/1/notification/proto`
- `/supercrypto/1/private-message/proto`

View File

@ -6,7 +6,7 @@ Waku takes a modular approach, providing a range of protocols that enable applic
## [Relay](https://rfc.vac.dev/spec/11/)
`Relay` protocol employs a Pub/Sub architecture to facilitate message routing among peers. It extends the [libp2p GossipSub protocol](https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/README.md) to create a privacy-focused peer-to-peer messaging protocol that enables secure communication channels, encryption, and protection against censorship. It also scales the Waku Network to accommodate many nodes efficiently.
`Relay` protocol employs a Pub/Sub architecture to facilitate the sending and receiving of messages among peers. It extends the [libp2p GossipSub protocol](https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/README.md) to create a privacy-focused peer-to-peer messaging protocol that enables secure communication channels, encryption, and protection against censorship. It also scales the Waku Network to accommodate many nodes efficiently.
## [RLN Relay](https://rfc.vac.dev/spec/17/)
@ -14,7 +14,7 @@ Waku takes a modular approach, providing a range of protocols that enable applic
## [Filter](https://rfc.vac.dev/spec/12/)
`Filter` protocol allows light nodes to selectively subscribe to specific messages transmitted by other peers using [content topics](/overview/concepts/content-topics). It is designed to be a lightweight alternative for accessing the `Relay` network, particularly tailored for devices with limited bandwidth.
`Filter` protocol allows light nodes to selectively subscribe to specific messages relayed by other peers using [content topics](/overview/concepts/content-topics). It is designed to be a lightweight alternative for accessing the `Relay` network, particularly tailored for devices with limited bandwidth.
:::info
`Filter` protocol helps optimize bandwidth usage, but it has fewer privacy guarantees as it must disclose the content topic to its peers to retrieve messages.

View File

@ -100,7 +100,7 @@ Rate Limit Nullifiers (RLN) are a construct based on zero-knowledge proofs that
### [Relay](/overview/concepts/protocols#relay)
Relay is a [protocol](#protocol) that extends the [GossipSub protocol](#gossipsub) to enable secure and censorship-resistant [message](#waku-message) dissemination among [peers](#peer) while preserving privacy. It also scales the [Waku Network](#waku) to accommodate many nodes efficiently.
Relay is a [protocol](#protocol) that extends the [GossipSub protocol](#gossipsub) to enable secure and censorship-resistant [message](#waku-message) sending and receiving among [peers](#peer) while preserving privacy. It also scales the [Waku Network](#waku) to accommodate many nodes efficiently.
### Resource-Limited

View File

@ -81,6 +81,10 @@ const config = {
label: "Run a Nwaku Node",
to: "/guides/run-nwaku-node",
},
{
label: "JavaScript Waku SDK",
to: "/guides/js-waku/",
},
],
},
{
@ -136,6 +140,10 @@ const config = {
to: "/guides/run-nwaku-node",
label: "Run a Nwaku Node",
},
{
to: "/guides/js-waku/",
label: "JavaScript Waku SDK",
},
],
},
{

View File

@ -67,6 +67,29 @@ const sidebars = {
"guides/nwaku/configure-discovery",
]
},
{
type: "category",
label: "JavaScript Waku SDK",
link: {
type: "doc",
id: "guides/js-waku/index",
},
items: [
"guides/js-waku/quick-start",
"guides/js-waku/relay-send-receive",
"guides/js-waku/light-send-receive",
"guides/js-waku/store-retrieve-messages",
"guides/js-waku/waku-create-app",
{
type: 'html',
value: '<a href="https://examples.waku.org" target="_blank" rel="noopener noreferrer" class="menu__link external-link">Examples<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M11.1918 4H3.42848V2.85715H13.1428V12.5714H11.9999V4.80813L3.83254 12.9755L3.02441 12.1674L11.1918 4Z" fill="white"/></svg>',
},
{
type: 'html',
value: '<a href="https://js.waku.org" target="_blank" rel="noopener noreferrer" class="menu__link external-link">API Documentation<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M11.1918 4H3.42848V2.85715H13.1428V12.5714H11.9999V4.80813L3.83254 12.9755L3.02441 12.1674L11.1918 4Z" fill="white"/></svg>',
},
]
},
{
type: "category",
label: "Reference",

Binary file not shown.

After

Width:  |  Height:  |  Size: 378 KiB