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.
Before you start, make sure you have the following dependencies installed.
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";
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.
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...
}
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);
}
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();
}, [])
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);
});
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);
});
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);
});
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);
})
Last modified 26d ago