chore: improve js-waku docs (#94)

* implement initial feedback

* remove relay guides
This commit is contained in:
LordGhostX 2023-07-18 19:51:12 +01:00 committed by GitHub
parent a671718f86
commit d1f053598a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 84 additions and 317 deletions

View File

@ -42,8 +42,7 @@ Check out the quick start guide and comprehensive tutorials to learn how to buil
| 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 |
| [Quick Start](/guides/js-waku/quick-start) | Quickly familiarize yourself with `js-waku` by setting up a Waku node and sending messages using the [Light Push](/overview/concepts/protocols#light-push) 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 |
| [Build React DApps Using @waku/react](/guides/js-waku/use-waku-react) | Learn how to use the [@waku/react](https://www.npmjs.com/package/@waku/react) package seamlessly integrate `js-waku` into a React application |

View File

@ -2,17 +2,17 @@
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). Check out the [installation guide](/guides/js-waku/#installation) for steps on adding `js-waku` to your project.
This guide provides quick steps to start using the `js-waku` SDK by setting up a Waku node and sending messages using the [Light Push protocol](/overview/concepts/protocols#light-push). Check out the [installation guide](/guides/js-waku/#installation) for steps on adding `js-waku` to your project.
## Create a Relay Node
## Create a Light Node
Use the `createRelayNode()` function to create a Relay Node and interact with the Waku Network:
Use the `createLightNode()` function to create a `Light Node` and interact with the Waku Network:
```js
import { createRelayNode } from "@waku/sdk";
import { createLightNode } from "@waku/sdk";
// Create and start a Relay Node
const node = await createRelayNode({ defaultBootstrap: true });
// Create and start a Light Node
const node = await createLightNode({ defaultBootstrap: true });
await node.start();
// Use the stop() function to stop a running node
@ -125,9 +125,9 @@ const ChatMessage = new protobuf.Type("ChatMessage")
.add(new protobuf.Field("message", 3, "string"));
```
## Send Messages Using Relay
## Send Messages Using Light Push
To send messages using the `Relay` protocol, create a new message object and use the `relay.send()` function:
To send messages using the `Light Push` protocol, create a new message object and use the `lightPush.send()` function:
```js
// Create a new message object
@ -140,8 +140,8 @@ const protoMessage = ChatMessage.create({
// Serialize the message using Protobuf
const serializedMessage = ChatMessage.encode(protoMessage).finish();
// Send the message using Relay
await node.relay.send(encoder, {
// Send the message using Light Push
await node.lightPush.send(encoder, {
payload: serializedMessage,
});
```

View File

@ -1,103 +0,0 @@
---
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 Relay 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
When the `emitSelf` flag is set to `true`, the node will emit sent message events to itself and invoke its 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
Check out the [Protobuf installation](/guides/js-waku/quick-start#create-a-message-structure) guide for 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
To receive messages using the `Relay` protocol, create a callback function to process the messages and use the `relay.subscribe()` function:
```js
// Create the callback function
const callback = (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);
};
// Subscribe to content topics and display new messages
const unsubscribe = await node.relay.subscribe([decoder], callback);
// 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. Check out the [relay-js](https://github.com/waku-org/js-waku-examples/tree/master/examples/relay-js), [relay-reactjs-chat](https://github.com/waku-org/js-waku-examples/tree/master/examples/relay-reactjs-chat), and [relay-angular-chat](https://github.com/waku-org/js-waku-examples/tree/master/examples/relay-angular-chat) examples for working demos.
:::

View File

@ -61,9 +61,7 @@ const callback = (wakuMessage) => {
};
// Set the query options
const queryOptions = {
pageSize: 5,
};
const queryOptions = {};
// Query the Store peer
await node.store.queryOrderedCallback(
@ -82,9 +80,7 @@ The `store.queryGenerator()` function provides more control and flexibility over
```js
// Set the query options
const queryOptions = {
pageSize: 5,
};
const queryOptions = {};
// Create the store query
const storeQuery = node.store.queryGenerator(
@ -128,16 +124,6 @@ const queryOptions = {
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:
@ -163,7 +149,7 @@ If you omit the `timeFilter` option, the query will start from the beginning or
### `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:
The `cursor` option specifies the starting index for retrieving messages. For example, consider a query that retrieves the first page messages and then continues with the next page:
```js
import { waku } from "@waku/sdk";
@ -174,26 +160,22 @@ const callback = (wakuMessage) => {
messages.push(wakuMessage);
};
// Retrieve the first 10 messages
// Retrieve the first page of 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
// Retrieve the next page of messages
// The message at the cursor index is excluded from the result
await node.store.queryOrderedCallback(
[decoder],
callback,
{
pageSize: 10,
cursor: cursor,
},
);

View File

@ -36,54 +36,30 @@ Next, install the `@waku/react` package using your preferred package manager:
<TabItem value="npm" label="npm">
```shell
npm install @waku/react @waku/sdk
npm install @waku/react
```
</TabItem>
<TabItem value="yarn" label="Yarn">
```shell
yarn add @waku/react @waku/sdk
yarn add @waku/react
```
</TabItem>
</Tabs>
## Create a Relay Node
Use the `useCreateRelayNode()` hook to create a Relay Node:
```js title="App.js"
import { useCreateRelayNode } from "@waku/react";
function App() {
// Create and start a Relay Node
const { node, error, isLoading } = useCreateRelayNode({
options: {
defaultBootstrap: true,
emitSelf: true,
}
});
// "node" is the created Relay Node
// "error" captures any error that occurs during node creation
// "isLoading" indicates whether the node is still being created
}
```
## Create a Light Node
Use the `useCreateLightNode()` hook to create a Light Node and specify the [protocols](/overview/concepts/protocols) for remote peers:
Use the `useCreateLightNode()` hook to create a [Light Node](/guides/js-waku/light-send-receive):
```js title="App.js"
import { useCreateLightNode } from "@waku/react";
import { Protocols } from "@waku/interfaces";
function App() {
// Create and start a Light Node and wait for remote peers
const { node, error, isLoading } = useCreateLightNode({
options: { defaultBootstrap: true },
protocols: [Protocols.LightPush, Protocols.Filter],
});
// "node" is the created Light Node
@ -92,49 +68,57 @@ function App() {
}
```
## Create an Encoder and Decoder
You can also use the `LightNodeProvider` [context provider](https://react.dev/reference/react/createContext#provider) to pass configuration options for creating a `Light Node`:
Use the `useCreateContentPair()` hook to create a message `encoder` and `decoder` pair:
```js title="index.js"
import { LightNodeProvider } from "@waku/react";
// Set the Light Node options
const NODE_OPTIONS = { defaultBootstrap: true };
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// Use the Light Node context provider
<LightNodeProvider options={NODE_OPTIONS}>
<App />
</LightNodeProvider>
</React.StrictMode>
);
```
```js title="App.js"
import { useCreateContentPair } from "@waku/react";
import { useWaku } from "@waku/react";
function App() {
// Choose a content topic
const contentTopic = "/waku-react-guide/1/message/utf8";
const ephemeral = false;
// Create a message encoder and decoder pair
const { encoder, decoder } = useCreateContentPair(contentTopic, ephemeral);
// "encoder" is the message encoder
// "decoder" is the message decoder
// Create and start a Light Node
const { node, error, isLoading } = useWaku();
}
```
## Send Messages Using Light Push
Use the `useLightPush()` hook to bind `Light Push` methods to a node and `encoder`:
Use the `useLightPush()` hook to bind [Light Push methods](/guides/js-waku/light-send-receive/#send-messages-using-light-push) to a node and `encoder`:
```js title="App.js"
import {
useCreateLightNode,
useCreateContentPair,
useLightPush,
} from "@waku/react";
import { Protocols } from "@waku/interfaces";
import { utf8ToBytes } from "@waku/sdk";
import {
utf8ToBytes,
createEncoder,
} from "@waku/sdk";
function App() {
// Create and start a Light Node and wait for remote peers
const { node, error, isLoading } = useCreateLightNode({
options: { defaultBootstrap: true },
protocols: [Protocols.LightPush, Protocols.Filter],
});
// Choose a content topic and create an encoder
const contentTopic = "/waku-react-guide/1/message/utf8";
const { encoder } = useCreateContentPair(contentTopic);
const encoder = createEncoder({ contentTopic });
// Wait for the node to finish loading before sending messages
// (isLoading === false)
@ -160,73 +144,86 @@ Wait for the node to finish loading before sending messages (`isLoading` === `fa
## Receive Messages Using Filter
Use the `useFilterMessages()` hook to receive messages from a `Filter` subscription:
Use the `useFilterMessages()` hook to receive messages from a [Filter subscription](/guides/js-waku/light-send-receive/#receive-messages-using-filter) and keep it updated:
```js title="App.js"
import {
useCreateLightNode,
useCreateContentPair,
useFilterMessages,
} from "@waku/react";
import { Protocols } from "@waku/interfaces";
import {
bytesToUtf8,
createDecoder,
} from "@waku/sdk";
function App() {
// Create and start a Light Node and wait for remote peers
const { node } = useCreateLightNode({
options: { defaultBootstrap: true },
protocols: [Protocols.LightPush, Protocols.Filter],
});
// Choose a content topic and create a decoder
const contentTopic = "/waku-react-guide/1/message/utf8";
const { decoder } = useCreateContentPair(contentTopic);
const decoder = createDecoder(contentTopic);
// Receive messages from Filter subscription
const { error, messages, isLoading } = useFilterMessages({ node, decoder });
console.log(messages);
// "error" captures any error that occurs while receiving messages
// "messages" contains a list of messages the subscription received
// "isLoading" indicates whether the node is still subscribing to Filter
// Wait for the messages to finish loading before processing them
// (isLoading === false)
messages.forEach((message) => {
console.log(bytesToUtf8(message.payload));
});
}
```
:::info
Wait for the messages to finish loading before processing them (`isLoading` === `false`).
:::
## Retrieve Messages Using Store
Use the `useStoreMessages()` hook to retrieve messages from the `Store` protocol:
Use the `useStoreMessages()` hook to retrieve messages from the [Store protocol](/guides/js-waku/store-retrieve-messages):
```js title="App.js"
import {
useCreateLightNode,
useCreateContentPair,
useStoreMessages,
} from "@waku/react";
import { Protocols, PageDirection } from "@waku/interfaces";
import {
bytesToUtf8,
createDecoder,
} from "@waku/sdk";
function App() {
// Create and start a Light Node and wait for remote peers
const { node } = useCreateLightNode({
options: { defaultBootstrap: true },
protocols: [Protocols.LightPush, Protocols.Filter],
});
// Choose a content topic and create a decoder
const contentTopic = "/waku-react-guide/1/message/utf8";
const { decoder } = useCreateContentPair(contentTopic);
const decoder = createDecoder(contentTopic);
// Set the query options
const options = {
pageDirection: PageDirection.BACKWARD,
pageSize: 20,
};
const options = {};
// Query the Store peer
const { error, messages, isLoading } = useStoreMessages({ node, decoder, options });
console.log(messages);
// "error" captures any error that occurs during message retrieval
// "messages" contains a list of messages retrieved from the Store peer
// "isLoading" indicates whether the node is still retrieving messages
// Wait for the messages to finish retrieving before processing them
// (isLoading === false)
messages.forEach((message) => {
console.log(bytesToUtf8(message.payload));
});
}
```
@ -234,115 +231,6 @@ function App() {
To explore the available query options, check out the [Store Query Options](/guides/js-waku/store-retrieve-messages#store-query-options) guide.
:::
## Using @waku/react Providers
The `@waku/react` package provides a collection of [context providers](https://react.dev/reference/react/createContext#provider) to pass configuration options throughout the component hierarchy:
### `RelayNodeProvider`
The `RelayNodeProvider` context provider passes configuration options for creating a Relay Node:
```js title="index.js"
import { RelayNodeProvider } from "@waku/react";
import { Protocols } from "@waku/interfaces";
// Set the Relay Node options
const NODE_OPTIONS = {
defaultBootstrap: true,
emitSelf: true,
};
// Set the remote peer connections to wait for
const PROTOCOLS = [Protocols.Relay];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// Use the Relay Node context provider
<RelayNodeProvider options={NODE_OPTIONS} protocols={PROTOCOLS}>
<App />
</RelayNodeProvider>
</React.StrictMode>
);
```
```js title="App.js"
import { useWaku } from "@waku/react";
function App() {
// Create and start a Relay Node
const { node, error, isLoading } = useWaku();
}
```
### `LightNodeProvider`
The `LightNodeProvider` context provider passes configuration options for creating a Light Node:
```js title="index.js"
import { LightNodeProvider } from "@waku/react";
import { Protocols } from "@waku/interfaces";
// Set the Light Node options
const NODE_OPTIONS = { defaultBootstrap: true };
// Set the remote peer connections to wait for
const PROTOCOLS = [
Protocols.LightPush,
Protocols.Filter,
];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// Use the Light Node context provider
<LightNodeProvider options={NODE_OPTIONS} protocols={PROTOCOLS}>
<App />
</LightNodeProvider>
</React.StrictMode>
);
```
```js title="App.js"
import { useWaku } from "@waku/react";
function App() {
// Create and start a Light Node
const { node, error, isLoading } = useWaku();
}
```
### `ContentPairProvider`
The `ContentPairProvider` context provider passes configuration options for creating an `encoder` and `decoder` pair:
```js title="index.js"
import { ContentPairProvider } from "@waku/react";
// Choose a content topic
const CONTENT_TOPIC = "/waku-react-guide/1/message/utf8";
const EPHEMERAL = false;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// Use the content pair context provider
<ContentPairProvider contentTopic={CONTENT_TOPIC} ephemeral={EPHEMERAL}>
<App />
</ContentPairProvider>
</React.StrictMode>
);
```
```js title="App.js"
import { useContentPair } from "@waku/react";
function App() {
// Create a message encoder and decoder pair
const { encoder, decoder } = useContentPair();
}
```
:::tip
You have successfully integrated `js-waku` into a React application using the `@waku/react` package. Check out the [web-chat](https://github.com/waku-org/js-waku-examples/tree/master/examples/web-chat) example for a working demo.
:::

View File

@ -86,7 +86,7 @@ When Discv5 is enabled and used with [DNS Discovery](#configure-dns-discovery),
To enable [Peer Exchange](/overview/concepts/peer-exchange) in a `nwaku` node, use the following configuration options:
- `peer-exchange`: Enables `Peer Exchange` on the node as a responder (disabled by default).
- `peer-exchange-node` (optional): ENR for bootstrap node that has the peer exchange protocol enabled.
- `peer-exchange-node` (optional): Multiaddr for bootstrap node that has the peer exchange protocol enabled.
```bash
./build/wakunode2 \

View File

@ -30,6 +30,7 @@ Here are the available node configuration options, along with their default valu
| `nat` | any | Specify method to use for determining public address. Must be one of: any, none, upnp, pmp, extip:<IP\> |
| `ext-multiaddr` | | External multiaddresses to advertise to the network. Argument may be repeated |
| `max-connections` | `50` | Maximum allowed number of libp2p connections |
| `max-relay-peers` | | Maximum allowed number of relay peers |
| `peer-store-capacity` | | Maximum stored peers in the peerstore |
| `peer-persistence` | `false` | Enable peer persistence |
@ -62,6 +63,7 @@ Here are the available node configuration options, along with their default valu
| `rln-relay-eth-contract-address` | | Address of membership contract on an Ethereum testnet |
| `rln-relay-cred-password` | | Password for encrypting RLN credentials |
| `rln-relay-tree-path` | | Path to the RLN merkle tree sled db (https://github.com/spacejam/sled) |
| `rln-relay-bandwidth-threshold` | `0 # to maintain backwards compatibility` | Message rate in bytes/sec after which verification of proofs should happen |
| `staticnode` | | Peer multiaddr to directly connect with. Argument may be repeated |
| `keep-alive` | `false` | Enable keep-alive for idle connections: true\|false |
| `topic` | `["/waku/2/default-waku/proto"]` | Default topic to subscribe to. Argument may be repeated |

View File

@ -69,13 +69,13 @@ const config = {
label: "About Waku",
},
{
to: "/powered-by-waku",
label: "Powered by Waku",
to: "/presentations",
label: "Presentations",
position: "left",
},
{
to: "/presentations",
label: "Presentations",
to: "/powered-by-waku",
label: "Powered by Waku",
position: "left",
},
{

View File

@ -78,6 +78,6 @@ def extract_config(config_path: str) -> str:
if __name__ == "__main__":
config_path = "https://raw.githubusercontent.com/waku-org/nwaku/master/apps/wakunode2/config.nim"
config_path = "https://raw.githubusercontent.com/waku-org/nwaku/master/apps/wakunode2/external_config.nim"
table_data = extract_config(config_path)
print(table_data)

View File

@ -72,7 +72,6 @@ const sidebars = {
},
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/use-waku-react",
@ -83,7 +82,7 @@ const sidebars = {
},
{
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>',
value: '<a href="https://js.waku.org" target="_blank" rel="noopener noreferrer" class="menu__link external-link">API Reference<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>',
},
]
},
@ -100,8 +99,8 @@ const sidebars = {
community: [
"community",
"contribute",
"powered-by-waku",
"presentations",
"powered-by-waku",
{
type: 'html',
value: '<a href="https://github.com/waku-org/bounties" target="_blank" rel="noopener noreferrer" class="menu__link external-link">Waku Bounties<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>',