SendingNetwork
  • OVERVIEW
    • Getting Started
    • FAQs
  • Network Instructional Articles
    • Basics
      • Introducing the Edge, WatchDog, and Guardian Nodes
      • Overview
      • Messaging Solution
      • Privacy Solution
      • Rich Communication Solution
      • Multi-Platform Solution
      • Decentralized Identity
      • Multiple Chat Modes
      • How It Works
      • Token Utility
      • The Team
    • Key Concepts
      • Decentralized Identity
      • Social Graphs
      • Edge Node
  • SDK Documentation
    • Glossary
    • JavaScript client SDK
      • DID
      • User
      • Message
      • Room
      • Contact
      • Social Graph
    • iOS client SDK
      • Push
      • DID
      • User
      • Message
      • Room
      • Contact
    • Android client SDK
      • User
      • Room
    • Java SDK
      • DID
      • Room
      • Message
    • Node.js SDK
      • DID
      • Room
      • Message
    • Unreal SDK
      • DID
      • User
      • Message
      • Room
    • Unity SDK
      • DID
      • Room
      • Message
    • Website chat widget SDK
      • Customization
      • DID
      • User
      • Room
      • Message
      • Other
    • Bot SDKs
      • Golang Bot SDK
        • DID
        • User
        • Room
        • Message
    • Extensible Message Interface
    • Push Notifications
    • Flutter SDK
      • DID
      • User
      • Message
      • Room
    • PHP SDK
      • DID
      • Room
      • User
    • Developer Key
  • Acquisition Kit
    • Social Boost Development Instructions
  • WatchDog Agent
    • WatchDog Agent Guide
    • WatchDog Agent Deployment Tutorial
      • Linux Deployment Tutorial
    • One-Click Deployment
  • Edge Node
    • Edge Node Deployment Tutorial
    • VPS Setup Guide
      • Google Cloud Platform (GCP)
      • Amazon Web Services (AWS)
      • Contabo
    • Check Node Stats with Auto-Reply Bot in SendingMe App
    • Alpha-3 Testnet FAQs
  • delegation node
    • Delegation Node Deployment Tutorial
  • Private Delegation Node
  • Use Cases
    • Wallet-to-Wallet Messaging
    • Dapp Notifications
    • Identity Verification
    • Gamer Acquisition
    • Cross-platform Trading
Powered by GitBook
On this page
  • Prerequisites
  • Build the Client
  • Step 1. Install
  • Step 2. Configure Developer Key
  • Step 3. Register
  • Step 4. Sync and Listen
  • Step 5. Create a room
  • Step 6. Invite users to the room
  • Step 7. Join the room with room ID
  • Step 8. Post messages to a room
  1. SDK Documentation

JavaScript client SDK

This quickstart is for using Sending.Network (SDN) on the client side in the browser, or front-end. Let's explore how to make a simple Sending.Network client with the ability to sync messages, create a chat room, and post messages in the room.

When you complete this quickstart, you’ll have a fully running application that can send and receive messages from the comfort of your own web browser.

Prerequisites

Before you start, make sure you have the following dependencies installed.

Components
Details

Node.js

NPM

Yarn

Sending.Network JavaScript SDK

Build the Client

Step 1. Install

Use npm or yarn to install the sdk package.

npm i sendingnetwork-js-sdk
# Or
yarn add sendingnetwork-js-sdk

Then you are free to import the package in your code:

import sdk from "sendingnetwork-js-sdk";

Step 2. Configure Developer Key

Kindly establish a secure key server for the proper management of your developer key. Additionally, it is necessary to outline the following API, which enables the widget to send a challenge to be signed by the key server.

To successfully complete the key verification, you need to provide a function called signWithDevKey. This function should be attached to the window object and will be called during widget login. Here is a snippet of code for your reference:

// Input Parameters: { message: string }
// Output Parameters: signature string
signWithDevKey = async ({ message }: any) => {
  if (!message) return;
  // Make a request to your backend API to sign the message and retrieve the signature.
  // Note: This example demonstrates the concept; implement this API in your backend.
  const response = await fetch(
  	'https://YOUR_KEY_SERVER/_api/appservice/sign',
    {
      method: 'POST',
      body: JSON.stringify({ message }),
    },
  );
  const { signature } = await response.json();
  return signature;
};

// Pseudo Code for Login Flow
login = async () => {
	// Other code logic, omitted here...
	const { message: lMessage, updated, random_server } = await this._client.preDiDLogin1(preloginParams);
	const devSign = await window.signWithDevKey({message: lMessage});
	const loginParams = {
		// Other parameters, omitted here...
		identifier: {
			// Other parameters, omitted here...
			app_token: devSign
		}
	}
	const { access_token, user_id } = await this._client.DIDLogin(loginParams);
	// Other code logic, omitted here...
}

Step 3. Register

Now, it's time to register a DID, creating a unique identifier in the P2P messaging network.

You can connect to a public node by configuring the baseUrl with https://portal0101.sending.network.

import sdk from "sendingnetwork-js-sdk";

const baseUrl = 'https://portal0101.sending.network'
const client = sdk.createClient({
  baseUrl,
});
 
const login = async () => {
    const prefix = "did:pkh:eip155:1:";
  const accounts = await window.ethereum.request({
    method: "eth_requestAccounts",
  });
  const [address] = accounts;
  const { data: [did] } = await client.getDIDList(address);
  const preloginParams = did ? { did } : { address: `${prefix}${address}` };
  const { message: lMessage, updated, random_server } = await client.preDiDLogin1(preloginParams);
  const sign = await window.ethereum.request({
    method: "personal_sign",
    params: [lMessage, address, ""],
  });
  const devSign = signWithDevKey({message: lMessage});
  const identifier = {
    did,
    address: did || `${prefix}${address}`,
    token: sign,
    app_token: devSign,
    message: lMessage
  };
  const deviceId = localStorage.getItem("mx_device_id") || null;
  const loginParams = {
    type: "m.login.did.identity",
    updated,
    identifier,
    random_server,
    device_id: deviceId,
    initial_device_display_name: this.defaultDeviceDisplayName
  };
 
  const { access_token, user_id } = await this._client.DIDLogin(loginParams);
  localStorage.setItem("sdn_access_token", access_token);
  localStorage.setItem("sdn_user_id", user_id);
  localStorage.setItem("sdn_user_address", address);
}

Step 4. Sync and Listen

The following code sets up the client that connects to the server. The client will start syncing and then listen for the response to get the latest state from the server:

client.startClient();
client.once('sync', function(state, prevState, res) {
    console.log(state); // state will be 'PREPARED' when the client is ready to use
});

Once the sync is complete, you can add listeners for events as follows.:

client.on("event", function(event){
    console.log(event.getType());
    console.log(event);
})

You can listen to all incoming events, but that would be too much data for our simple application. Instead, let's listen to events that happens after you join a chat room:

client.on("Room.timeline", function(event, room, toStartOfTimeline) {
    console.log(event.event);
});

Call client.stopClient at the end of the component's lifecycle. For example:

useEffect(() => {
    client.startClient();
    return () => client.stopClient();
}, [])

Step 5. Create a room

Create a chat room and give it a name.

client.createRoom({
    name:"YOUR_ROOM_NAME", 
}).then((room_info) => {
    console.log(room_info);
}).catch(() => {
    console.log(err);
});

Step 6. Invite users to the room

To invite a friend, just call the invite() method and specify the user id and the chat room id.

var room_id = "THE_ROOM_ID";
var user_id = "THER_USER_ID_YOU_WANT_INVITE";

client.invite(room_id, user_id).then(() => {
    //console.log("invite user successfully");
}).catch((err) => {
    console.log(err);
});

Step 7. Join the room with room ID

You can also apply to join a room by specifying the room ID.

client.joinRoom($roomId).then(room=>{
    //console.log("joined successfully");
}).catch((err) => {
    console.log(err);
});

Step 8. Post messages to a room

To post a message, create a content object and specify a target room.

var room_id = "THE_ROOM_ID";

var content = {
    "body": "Hello World",
    "msgtype": "m.text"
};

client.sendEvent(room_id, "m.room.message", content, "").then((res) => {
    //console.log("post message successfully");
}).catch((err) => {
    console.log(err);
})
PreviousGlossaryNextDID

Last updated 1 year ago

Download the latest version

Download the latest version

Install Yarn

You may find the source code

You will need a developer key to access the Edge Network. For further insight into the mechanism and to request a developer key, please consult the provided guide .

here
here
here
here
here