Skip to main content

PubSub

Pub/Sub​

This is a quick tutorial around experimental raw Pub/Sub capabilities of Web3MQ.

Installation​

Install Web3MQ's JS SDK using a package manager of your choice

npm install @web3mq/client
or
yarn add @web3mq/client

Initialize Client and Connect to Web3MQ Network​

In order to connect to the Web3MQ Network, both users and developers authenticate through wallet signatures, we demonstrate below with an Ethereum wallet via Metamask, but Web3MQ is built to be compatible with wallets across different chains.

Initialize Client​

note

While we are committed to building an open and collectively owned public good, our early stage testnet requires an API key in order to connect. This is to control capacity to make sure that each early partner and developer is able to build a great experience on top of Web3MQ. Apply here.

As Web3MQ is a federated network, our default JS SDK client has a method to help you connect to the best node for you.

Simply calling Client.init without connectUrl or an empty string returns a url of the best node determined for you, and this url can be stored locally.

import { Client } from '@web3mq/client';

// You can save the bestEndpointUrl locally to skip endpoint search next time, which will save time, and
const bestEndpointUrl = await Client.init({
connectUrl: '', //
app_key: 'app_key', // temporary authorization key obtained by applying, will be removed in future testnets and mainnet
});

Calling Client.init with a specific connectUrl forces the client to connect to that specific node. When bestEndpointUrl is stored, it might be time-saving to connect directly instead of running the search again.

import { Client } from '@web3mq/client';

const fastUrl = await Client.init({
connectUrl: bestEndpointUrl, // takes in a valid endpoint url as input, when this paramter is given, client will always connect to that specific node.
app_key: 'app_key', // Appkey applied from our team
});

API endpoints​

During this initial testing phase, we've hosted complete networks of Web3MQ nodes in different regions around the globe. Connect to these endpoints below, to access the Web3MQ Testnet.

Sign with wallet to register user and obtain message encryption keys​

For any first-time user of Web3MQ's network, you'll need to register on Web3MQ's network. Web3MQ's JS SDK takes care of the key generation process and subsequent wallet signing process. Client.register.signMetaMask is a utility method that does this automatically.

Code​

// You must ensure that the Client.init initialization is complete before running this
const { PrivateKey, PublicKey } = await Client.register.signMetaMask({
signContentURI: 'https://www.web3mq.com', // your signContent URI
EthAddress: 'your eth address', // *Not required* your eth address, if not use your MetaMask eth address
});

console.log(PrivateKey, PublicKey);

// Keep your private key in a safe place, this is for demo purposes only
localStorage.setItem('PRIVATE_KEY', PrivateKey);
localStorage.setItem('PUBLICKEY', PublicKey);

Get Client Instance​

Code​

const keys = { PrivateKey, PublicKey };

const client = Client.getInstance(keys);

Create topic​

After initializing the client and registering your user, the next step is to create a topic.

Code​

client.topic.createTopic('topicName');
const handleCreate = async () => {
const data = await client.topic.createTopic(topicName);
console.log(data);
};

<button onClick={handleCreate}>createGroup</button>;

Publish Message to Topic​

Now that we've created a topic, let's try publishing a message to the topic we've just created.

Code​

const params = {
topicid: 'topicId',
title: 'test title',
content: 'test content',
};

client.topic.publishTopicMessage(params);
const handlePublishMsg = async () => {
const params = {
topicid: topicId,
title: 'test title',
content: 'test content',
};
await client.topic.publishTopicMessage(params);
};

<button onClick={handlePublishMsg}>publish Msg</button>;

Subscribe Topic​

Subscribe to topics to receive messages.

tip

This subscription function only tells the Web3MQ network that the user wants to subscribe to a topic. This is not where applications subscribe to the actual data feed via a WebSocket persistent connection. This happens in the notifications section below.

Code​

client.topic.subscribeTopic('topicId');
const handleSubscribe = async () => {
const data = await client.topic.subscribeTopic(topicId);
console.log(data);
};
<button onClick={handleSubscribe}>Subscribe Topic</button>;

Receive Notifications​

Each Web3MQ account is equipped with a notifications queue, currently, all subscriptions go to this notifications queue, and applications can subscribe to this notifications queue for real-time content, data, and event updates.

Code​

const handleEvent = (event: { type: string }) => {
const { type } = event;
if (type === 'notification.getList') {
console.log('notification list -------', client.notify.notificationList);
}
};

client.on('notification.getList', handleEvent);
const [notifyList, setNotifyList] = useState<any>([]);

const handleEvent = (event: { type: string }) => {
const { type } = event;
if (type === 'notification.getList') {
console.log('notification list -------', client.notify.notificationList);
}
};

useEffect(() => {
client.on('notification.getList', handleEvent);
return () => {
client.off('notification.getList', handleEvent);
};
}, [notifyList]);

<div>
<h1>Notify List</h1>
{
notifyList?.map((item: any, idx: number) => (
<div key={item.timestamp}>
{`notify${idx + 1}-------title:`}
<b>{item.title}</b>, content: <b>{item.content}</b>
</div>
));
}
</div>