Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@pushprotocol/restapi

Package Overview
Dependencies
Maintainers
1
Versions
251
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pushprotocol/restapi

This package gives access to Push Protocol (Push Nodes) APIs. Visit [Developer Docs](https://push.org/docs) or [Push.org](https://push.org) to learn more.

  • 0.0.1-alpha.79
  • npm
  • Socket score

Version published
Weekly downloads
2.4K
increased by22.05%
Maintainers
1
Weekly downloads
 
Created
Source

restapi

This package gives access to Push Protocol (Push Nodes) APIs. Visit Developer Docs or Push.org to learn more.

Index

How to use in your app?

Installation

yarn add @pushprotocol/restapi@latest

or

npm install @pushprotocol/restapi@latest

Note - ethers is an optional peer dependency and is required only when sdk is used with ethers signer.

Import SDK

import { PushAPI } from '@pushprotocol/restapi';

About generating the "signer" object for different platforms

When using in SERVER-SIDE code:

const ethers = require('ethers');
const PK = 'your_channel_address_secret_key';
const Pkey = `0x${PK}`;
const _signer = new ethers.Wallet(Pkey);

When using in FRONT-END code:

// any other web3 ui lib is also acceptable
import { useWeb3React } from "@web3-react/core";
.
.
.
const { account, library, chainId } = useWeb3React();
const _signer = library.getSigner(account);

About blockchain agnostic address format

In any of the below methods (unless explicitly stated otherwise) we accept either -

  • CAIP format: for any on chain addresses We strongly recommend using this address format. Learn more about the format and examples. (Example : eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb)

  • ETH address format: only for backwards compatibility. (Example: 0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb)

Chat blockchain agnostic address format

Note - For chat related apis, the address is in the format: eip155:<address> instead of eip155:<chainId>:<address>, we call this format Partial CAIP (Example : eip155:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb)

SDK Features

Manage User

APIs to Initialise User and User APIs.

Initialize

// Initialize PushAPI class instance
const userAlice = await PushAPI.initialize(signer, {
  env: 'staging',
});

Parameters

ParamTypeDefaultRemarks
signerSignerType-Ethers or Viem Signer.
options *PushAPIInitializeProps-Optional configuration properties for initializing the PushAPI.
options.env *ENVstagingAPI env - 'prod', 'staging', 'dev'.
options.progressHook*(progress: ProgressHookType) => void-A callback function to receive progress updates during initialization.
options.account *string-The account to associate with the PushAPI. If not provided, it is derived from signer.
options.version *stringENC_TYPE_V3The encryption version to use for the PushAPI.
options.versionMeta *{ NFTPGP_V1 ?: { password: string } }-Metadata related to the encryption version, including a password if needed, and reset for resetting nft profile
options.autoUpgrade *booleantrueIf true, upgrades encryption keys to the latest encryption version.
options.origin *string-Specify origin or source while creating a Push Profile.

* - Optional


Reinitialize

// Reinitialize PushAPI for fresh start of NFT Account
// Reinitialize only succeeds if the signer account is the owner of the NFT
await userAlice.reinitialize({
  versionMeta: { NFTPGP_V1: { password: 'NewPassword' } },
});

Parameters

ParamTypeDefaultRemarks
optionsPushAPIInitializeProps-Optional configuration properties for initializing the PushAPI.
options.versionMeta{ NFTPGP_V1 ?: password: string }-Metadata related to the encryption version, including a password if needed.

Fetch User Info

// userAlice.info({options?})
const response = await userAlice.info();

Parameters:

ParamTypeDefaultRemarks
optionsInfoOptions-Optional configuration properties
-options.overrideAccount-The account for which info is retrieved, can override to get info of other accounts not owned by the user. If not provided, it is derived from signer.

Fetch Profile Info

// userAlice.profile.info({options?})
const response = await userAlice.profile.info();

Parameters:

ParamTypeDefaultRemarks
optionsInfoOptions-Optional configuration properties
-options.overrideAccount-The account for which info is retrieved, can override to get info of other accounts not owned by the user. If not provided, it is derived from signer.

Update Profile Info

// Update Push Profile
// userAlice.profile.update({options?})
const response = await userAlice.profile.update({
  name: 'Alice',
  description: 'Alice is a software developer',
  picture: imageInBase64Format, // base64 encoded image
});
ParamTypeDefaultRemarks
optionsobject-Configuration options for updating profile
options.name *string-Profile Name
options.description *string-Profile Description
options.picture *string-Profile Picture

* - Optional


Fetch Encryption Info

// Fetch Encryption Info
const aliceEncryptionInfo = await userAlice.encryption.info();

Update Encryption

// userAlice.encryption.update(ENCRYPTION_TYPE, {options?})
// Wallet User Update,
// Usually not required as it's handled internally by the SDK to automatically update to recommended encryption type
const walletAlice = await userAlice.encryption.update(
  CONSTANTS.USER.ENCRYPTION_TYPE.PGP_V3
);

// NFT User Update
// Should be done when the NFT is transferred to a different user
// so messages and connections can be migrated to the new user
const nftAlice = await userAlice.encryption.update(
  CONSTANTS.USER.ENCRYPTION_TYPE.NFTPGP_V1,
  {
    versionMeta: {
      NFTPGP_V1: {
        password: 'new_password',
      },
    },
  }
);
ParamTypeDefaultRemarks
options *object-Optional Configuration for updating encryption
options.versionMeta*{ NFTPGP_V1 ?: { password : string} }-New Password ( In case of NFT Profile )

* - Optional


For Push Notifications

Initializing User is the first step before proceeding to sending/interacting with Notification APIs. Please refer Initialize User Section

Fetch Inbox Or Spam notifications

// lists feeds
const aliceInfo = await userAlice.notification.list('INBOX');

Parameters:

ParameterTypeDefaultDescription
spamINBOX or SPAMINBOXA string representing the type of feed to retrieve.
options*object-An object containing additional options for filtering and pagination.
options.account*string-Account in full CAIP
options.channels*string[] -An array of channels to filter feeds by.
options.page*number-A number representing the page of results to retrieve.
options.limit*number-A number representing the maximum number of feeds to retrieve per page.
options.raw*boolean-A boolean indicating whether to retrieve raw feed data.

* - Optional


Fetch user subscriptions

// fetches list of channels to which the user is subscribed
const subscriptions = await userAlice.notification.subscriptions();

Parameters:

ParameterTypeDefaultDescription
options*object-An object containing additional options for subscriptions.
options.account*string-Account in supported address format.
options.page*number-page of results to retrieve.
options.limit*number-represents the maximum number of subscriptions to retrieve per page.

* - Optional


Subscribe to a channel

// subscribes to a channel
const subscribeStatus = await userAlice.notification.subscribe(channelInCAIP, {
  settings,
});

Parameters:

ParameterTypeDefaultDescription
channelstring-Channel/Alias address in CAIP format
settings*objects[] -Contain array of individual setting object

Individual setting object:

ParamTypeSubtypeDefaultRemarks
settingobject--Individual setting object
-enabledbooleantrueIndicates if setting is enabled or disabled
-valuestring-The value set by the user

* - Optional


Unsubscribe to a channel

// unsubscribes to the channel
const unsubscribeResponse = await userAlice.notification.unsubscribe(
  channelAddressInCAIP
);

Parameters:

ParameterTypeDefaultDescription
channelstring-Channel/Alias address in CAIP format

* - Optional


Channel information

// fetches information about the channel
const channelInfo = await userAlice.channel.info(channelAddressInCAIP);

Parameters:

ParameterTypeDefaultDescription
channel*string-Channel address in CAIP format

* - Optional


Search Channels

// returns channel matching the query
const searchResult = await userAlice.channel.search('push');

Parameters:

ParameterTypeDefaultDescription
querystring-The search query to find channels.
options*ChannelSearchOptions-Configuration options for the search.
options.page*number-The page of results to retrieve. Default is set to 1
options.limit*number-The maximum number of channels to retrieve per page. Default is set to 10

* - Optional


Get Subscribers Of A Channel

// userAlice.channel.subscribers({options?})
const channelSubscribers = await userAlice.channel.subscribers();

Parameters:

ParamTypeSubtypeDefaultRemarks
optionsobject--Configuration options for retrieving subscribers.
-options.channelstringDerived from signerChannel address in chain specific wallet format. If no channel address is passed, then signer is used to derive the channel
-options.pagenumber-A number representing the page of results to retrieve.
-options.limitnumber-Represents the maximum number of subscriptions to retrieve per page
-options.settingbooleanfalseA boolean flag if when set to true, fetches user settings along with the subscriber
-options.categorynumber-Filters out subscribers that have enabled a specific category of notification settings

* - Optional


Send a notification

// sends a notification
// userAlice.channel.send([recipients], {options?})
const sendNotifRes = await userAlice.channel.send(['*'], {
  notification: { title: 'test', body: 'test' },
});

Parameters:

ParamTypeRemarks
recipientsstring[]An array of recipient addresses passed in any supported wallet address format. Possible values are: Broadcast -> [*], Targeted -> [0xA], Subset -> [0xA, 0xB], see types of notifications for more info.
optionsNotificationOptionsConfiguration options for sending notifications.
options.notificationINotificationAn object containing the notification's title and body. (Mandatory)
options.notification.titlestringThe title for the notification. If not provided, it is taken from notification.title.
options.notification.bodystringThe body of the notification. If not provided, it is taken from notification.body.
options.payload*IPayloadAn object containing additional payload information for the notification.
options.payload.title*stringThe title for the notification. If not provided, it is taken from notification.title.
options.payload.body*stringThe body of the notification. If not provided, it is taken from notification.body.
options.payload.cta*stringCall to action for the notification.
options.payload.embed*stringMedia information like image/video links
options.payload.category*stringDon't pass category if you are sending a generic notification. Notification category represents index point of each individual settings. Pass this if you want to indicate what category of notification you are sending (If channel has settings enabled). For example, if a channel has 10 settings, then a notification of category 7 indicates it's a notification sent for setting 7, if user has turned setting 7 off then Push ndoes will stop notif from getting to the user.
options.payload.meta*{ domain?: string, type: string, data: string }Metadata for the notification, including domain, type, and data.
options.config*IConfigAn object containing configuration options for the notification.
options.config.expiry*numberExpiry time for the notification in seconds
options.config.silent*booleanIndicates whether the notification is silent.
options.config.hidden*booleanIndicates whether the notification is hidden.
options.advanced*IAdvanceAn object containing advanced options for the notification.
options.advanced.graph*{ id: string, counter: number }Advanced options related to the graph based notification.
options.advanced.ipfs*stringIPFS information for the notification.
options.advanced.minimal*stringMinimal Payload type notification.
options.advanced.chatid*stringFor chat based notification.
options.advanced.pgpPrivateKey*stringPGP private key for chat based notification.
options.channel*stringChannel address in CAIP. Mostly used when a delegator sends a notification on behalf of the channel

* - Optional


Create a channel

// creates a channel
// userAlice.channel.create({options})
const response = await userAlice.channel.create({
  name: 'Test Channel',
  description: 'Test Description',
  icon: imageBase64Format,
  url: 'https://push.org',
});

Parameters:

ParamTypeDefaultRemarks
optionsobject-Configuration options for creating a channel
options.namestring-The name of the channel
options.descriptionstring-A description of the channel
options.iconstring (base64 encoded)-The channel's icon in base64 encoded string format
options.urlstring-The URL associated with the channel
options.aliasstring-alias address in in chain specific wallet format
options.progresshook(progress) => void-A callback function that's called during channel creation progress, see progress object

* - Optional

Optional: Informs about individual progress stages during channel creation if progresshook is function is passed during channel creation API call.

ParamTypeDefaultRemarks
progressobject-progress object that is passed in the callback
Progress.idstring-Predefined, ID associated with the progress objects
Progress.levelstring-Predefined, Level associated with the progress objects
Progress.titlestring-Predefined, title associated with the progress objects
Progress.infostring-Predefined, info associated with the progress objects

Progress object details

Progress.idProgress.levelProgress.titleProgress.info
PUSH-CHANNEL-CREATE-01INFOUploading data to IPFSThe channel’s data is getting uploaded to IPFS
PUSH-CHANNEL-CREATE-02INFOApproving PUSH tokensGives approval to Push Core contract to spend 50 $PUSH
PUSH-CHANNEL-CREATE-03INFOChannel is getting createdCalls Push Core contract to create your channel
PUSH-CHANNEL-CREATE-04SUCCESSChannel creation is done, Welcome to Push EcosystemChannel creation is completed
PUSH-CHANNEL-UPDATE-01INFOUploading new data to IPFSThe channel’s new data is getting uploaded to IPFS
PUSH-CHANNEL-UPDATE-02INFOApproving PUSH tokensGives approval to Push Core contract to spend 50 $PUSH
PUSH-CHANNEL-UPDATE-03INFOChannel is getting updatedCalls Push Core contract to update your channel details
PUSH-CHANNEL-UPDATE-04SUCCESSChannel is updated with new dataChannel is successfully updated
PUSH-ERROR-02ERRORTransaction failed for a function callTransaction failed

Update channel information

// updates channel info
// userAlice.channel.update({options?})
const updateChannelRes = await userAlice.channel.update({
  name: newChannelName,
  description: newChannelDescription,
  url: newChannelURL,
  icon: newBase64FormatImage,
  alias: newAliasAddressInCAIP,
});

Parameters:

ParameterTypeDefaultDescription
options--Configuration options for creating a channel.
options\.name string-New name of the channel.
options.descriptionstring-New description of the channel.
options.iconstring (base64 encoded)-The channel's new icon in base64 encoded string format.
options.urlstring-New URL associated with the channel.
options.alias*string-New alias address in CAIP
options.progresshook*() => void-A callback function to execute when the channel updation progresses.

* - Optional

Optional: Informs about individual progress stages during channel creation if progresshook is function is passed during channel creation API call.

ParamTypeDefaultRemarks
progressobject-progress object that is passed in the callback
Progress.idstring-Predefined, ID associated with the progress objects
Progress.levelstring-Predefined, Level associated with the progress objects
Progress.titlestring-Predefined, title associated with the progress objects
Progress.infostring-Predefined, info associated with the progress objects

Progress object details

Progress.idProgress.levelProgress.titleProgress.info
PUSH-CHANNEL-CREATE-01INFOUploading data to IPFSThe channel’s data is getting uploaded to IPFS
PUSH-CHANNEL-CREATE-02INFOApproving PUSH tokensGives approval to Push Core contract to spend 50 $PUSH
PUSH-CHANNEL-CREATE-03INFOChannel is getting createdCalls Push Core contract to create your channel
PUSH-CHANNEL-CREATE-04SUCCESSChannel creation is done, Welcome to Push EcosystemChannel creation is completed
PUSH-CHANNEL-UPDATE-01INFOUploading new data to IPFSThe channel’s new data is getting uploaded to IPFS
PUSH-CHANNEL-UPDATE-02INFOApproving PUSH tokensGives approval to Push Core contract to spend 50 $PUSH
PUSH-CHANNEL-UPDATE-03INFOChannel is getting updatedCalls Push Core contract to update your channel details
PUSH-CHANNEL-UPDATE-04SUCCESSChannel is updated with new dataChannel is successfully updated
PUSH-ERROR-02ERRORTransaction failed for a function callTransaction failed

Verify a channel

const verifyChannelRes = await userAlice.channel.verify(channel);

Parameters:

ParameterTypeDefaultDescription
channelstring-Channel address in CAIP to be verified

Create channel Setting

// creates channel settings
const createChannelSettingRes = userAlice.channel.setting([
  {
    type: 1, // Boolean type
    default: 1,
    description: 'Receive marketing notifications',
  },
  {
    type: 2, // Slider type
    default: 10,
    description: 'Notify when loan health breaches',
    data: { upper: 100, lower: 5, ticker: 1 },
  },
]);

Parameters:

PropertyTypeDefaultDescription
typenumber-The type of notification setting. 1 for boolean type and 2 for slider type
defaultnumber-The default value for the setting.
descriptionstring-A description of the setting.
data.upper*number-Valid for slider type only. The upper limit for the setting.
data.lower*number-Valid for slider type only. The lower limit for the setting.
data.ticker*numberValid for slider type only. The ticker by which the slider moves.

| * - Optional


Get delegators information

// fetch delegate information
const delegates = await userAlice.channel.delegate.get();

Parameters:

ParameterTypeDefaultDescription
options*ChannelInfoOptions-Configuration options for retrieving delegator information.
options.channel*string-channel address in CAIP

* - Optional


Add delegator to a channel or alias

// adds a delegate
const addedDelegate = await userAlice.channel.delegate.add(delegate);

Parameters:

ParameterTypeDefaultDescription
delegatestring-delegator address in CAIP
Note: Support for contract interaction via viem is coming soon

Remove delegator from a channel or alias

// removes a delegate
const removeDelegate = await userAlice.channel.delegate.remove(delegate);

Parameters:

ParameterTypeDefaultDescription
delegatestring-delegator address in CAIP
Note: Support for contract interaction via viem is coming soon

Alias Information

// fetch alias info
const aliasInfo = userAlice.channel.alias.info({
  alias: aliasAddress,
  aliasChain: 'POLYGON',
});

Parameters:

ParamTypeDefaultDescription
optionsobject-Configuration options for retrieving alias information.
options.aliasstring-The alias address
options.aliasChainALIAS_CHAIN-The name of the alias chain, which can be 'POLYGON' or 'BSC' or 'OPTIMISM' or 'POLYGONZKEVM'

Stream Notifications

// userAlice.stream(listen, {options?})
// Initial setup
const stream = await userAlice.initStream([CONSTANTS.STREAM.NOTIF], {
  filter: {
    channels: ['*'], // pass in specific channels to only listen to those
    chats: ['*'], // pass in specific chat ids to only listen to those
  },
  connection: {
    retries: 3, // number of retries in case of error
  },
  raw: false, // enable true to show all data
});

// Listen for notifications events
stream.on(CONSTANTS.STREAM.NOTIF, (data: any) => {
  console.log(data);
});

// Connect stream, Important to setup up listen events first
stream.connect();

// stream supports other products as well, such as STREAM.CHAT, STREAM.CHAT_OPS
// more info can be found at push.org/docs/chat

Parameters:

ParamTypeDefaultRemarks
listenconstant-can be CONSTANTS.STREAM.CHAT, CONSTANTS.STREAM.CHAT_OPS, CONSTANTS.STREAM.NOTIF, CONSTANTS.STREAM.CONNECT, CONSTANTS.STREAM.DISCONNECT
options*PushStreamInitializeProps-Optional configuration properties for initializing the stream.
options.filter*object-Option to configure to enable listening to only certain chats or notifications.
options.filter.channels*array of strings['*']pass list of channels over here to only listen to notifications coming from them.
options.filter.chats*array of strings['*']pass list of chatids over here to only listen to chats coming from them.
options.connection*object-Option to configure the connection settings of the stream
options.connection.retries*number3Number of automatic retries incase of error
options.raw*booleanfalseIf enabled, will also respond with meta data useful in verifying the integrity of incoming chats or notifications among other things.

Stream Notification Events

Listen eventsWhen is it triggered?
CONSTANTS.STREAM.NOTIFWhenever a new notification is emitted for the wallet.
CONSTANTS.STREAM.CONNECTWhenever the stream establishes connection.
CONSTANTS.STREAM.DISCONNECTWhenever the stream gets disconnected.

For Push Chat

Initializing User is the first step before proceeding to Chat APIs. Please refer Manage User Section

Fetch List of Chats

// List all chats
const aliceChats = await userAlice.chat.list('CHATS');
// List all chat requests
const aliceRequests = await userAlice.chat.list('REQUESTS');
ParamTypeDefaultRemarks
typeCHATS or REQUESTS-Type of Chats to be listed
options *Object-Optional configuration properties for listing chat
options.page *number1The page number for pagination
options.limit *number10The maximum number of items to retrieve per page

* - Optional


Fetch Latest Chat

// Latest Chat message with the target(bob) user
const aliceChats = await userAlice.chat.latest(bobAddress);
ParamTypeDefaultRemarks
recipientstring-Target DID ( For Group Chats target is chatId, for 1 To 1 chat target is Push DID )

Fetch Chat History

// userAlice.chat.history(recipient. {options?})
const aliceChatHistoryWithBob = await userAlice.chat.history(bobAddress);
ParamTypeDefaultRemarks
recipientstring-Target DID ( For Group Chats target is chatId, for 1 To 1 chat target is Push DID )
options *object-Optional Configuration for fetching chat history
options.reference*string or null-Refers to message refernce hash from where the previous messages are fetched. If null, messages are fetched from latest message
options.limit *number10No. of messages to be loaded

* - Optional


Send Message

// Alice sends message to bob
const aliceMessagesBob = await userAlice.chat.send(bobAddress, {
  content: 'Hello Bob!',
  type: 'Text',
});
ParamTypeDefaultRemarks
recipientstring-Recipient ( For Group Chats target is chatId, for 1 To 1 chat target is Push DID )
optionsobject-Configuration for message to be sent
options.type *Text or Image or Audio or Video or File or MediaEmbed or GIF or Meta or Reaction or Receipt or Intent or Reply or Composite-Type of message Content
options.contentstring or {type: TextorImageorAudioorVideoorFileorMediaEmbedorGIF ; content: string} [For Reply] or {type: TextorImageorAudioorVideoorFileorMediaEmbedorGIF ; content: string}[] [For Composite]-Message Content
options.reference *string-Message reference hash ( Only available for Reaction & Reply Messages )
options.info *{ affected : string[]: arbitrary?: { [key: string]: any } }-Message reference hash ( Only available for Meta & UserActivity Messages )

* - Optional


Accept Chat Request

// Accept Chat Request of Alice
const bobAcceptAliceRequest = await userBob.chat.accept(aliceAddress);
ParamTypeDefaultRemarks
recipientstring-Target ( For Group Chats target is chatId, for 1 To 1 chat target is Push Account )

Reject Chat Request

// Accept Chat Request of alice
await userBob.chat.reject(aliceAddress);
ParamTypeDefaultRemarks
recipientstring-Target ( For Group Chats target is chatId, for 1 To 1 chat target is Push Account )

Block Chat User

// Block chat user
const AliceBlocksBob = await userAlice.chat.block([bobAddress]);
ParamTypeDefaultRemarks
usersstring[]-Users to be blocked.

Unblock Chat User

// Unblock chat user
const AliceUnblocksBob = await userAlice.chat.unblock([bobAddress]);
ParamTypeDefaultRemarks
usersstring[]-Users to be unblocked.

Create Group

// Create a Group
// userAlice.chat.group.create(name, {options?})
const createdGroup = await userAlice.chat.group.create(name);
ParamTypeDefaultRemarks
namestring-The name of the group to be created.
options *object-Optional Configuration for creating group.
options.description *string-A description of the group.
options.image *string-Image for the group.
options.members *string[][]An array of member DID.
options.admins *string[]-An array of admin DID.
options.private *booleanfalseIndicates if the group is private.
options.rules *any[]-Conditions for entry to the group.

* - Optional


Fetch Group Info

// Fetch Group Info
const fetchGroupInfo = await userAlice.chat.group.info(groupChatId);
ParamTypeDefaultRemarks
chatIdstring-Group ChatId

Fetch Group Permissions

// Fetch Group Permissions
const fetchGroupPermissions = await userAlice.chat.group.permissions(
  groupChatId
);
ParamTypeDefaultRemarks
chatIdstring-Group ChatId

Update Group

// Update Group Info
// userAlice.chat.group.update(chatid, {options?})
const updatedGroup = await userAlice.chat.group.update(chatid, options);
ParamTypeDefaultRemarks
chatIdstring-Unique identifier of the group.
options *object-Optional Configuration for updating group.
options.name *string-Updated Group Name
options.description*string-Updated Description
options.image*string(base 64 format)-Updated Image
options.private*booleanfalseIndicates if the group is private.
options.rules *any[]-Define conditions such as token gating, nft gating, custom endpoint for joining or sending message in a group. See conditional group gating to understand rule engine and how to fine tune conditional rules of your group Rules

* - Optional


Add To Group

// await userAlice.chat.group.add(chatid, {options?})
const addAdminToGroup = await userAlice.chat.group.add(groupChatId, {
  role: 'ADMIN', // 'ADMIN' or 'MEMBER'
  accounts: [account1, account2],
});
ParamTypeDefaultRemarks
chatIdstring-Unique identifier of the group.
optionsobject-Configuration for adding participants to group.
options.roleADMIN or MEMBER-Role of added participant
options.accountsstring[]-Added participant addresses

Remove From Group

// await userAlice.chat.group.remove(chatid, {options?})
const removeAdminFromGroup = await userAlice.chat.group.remove(groupChatId, {
  role: 'ADMIN', // 'ADMIN' or 'MEMBER'
  accounts: [account1, account2],
});
ParamTypeDefaultRemarks
chatIdstring-Unique identifier of the group.
optionsobject-Configuration for adding participants to group.
options.roleADMIN or MEMBER-Role of added participant
options.accountsstring[]-Added participant addresses

Join Group

const joinGroup = await userAlice.chat.group.join(groupChatId);
ParamTypeDefaultRemarks
chatIdstring-Unique identifier of the group.

Leave Group

// Leave Group
const leaveGrp = await userAlice.chat.group.leave(groupChatId);
ParamTypeDefaultRemarks
chatIdstring-Unique identifier of the group.

Reject Group Joining Request

// Reject Group Request
await userAlice.chat.group.reject(groupChatId);
ParamTypeDefaultRemarks
chatIdstring-Unique identifier of the group.

Stream Chat Events

// Initialize stream to listen for events:
const stream = await userAlice.initStream(
  [
    CONSTANTS.STREAM.CHAT, // Listen for chat messages
    CONSTANTS.STREAM.NOTIF, // Listen for notifications
    CONSTANTS.STREAM.CONNECT, // Listen for connection events
    CONSTANTS.STREAM.DISCONNECT, // Listen for disconnection events
  ],
  {
    // Filter options:
    filter: {
      // Listen to all channels and chats (default):
      channels: ['*'],
      chats: ['*'],

      // Listen to specific channels and chats:
      // channels: ['channel-id-1', 'channel-id-2'],
      // chats: ['chat-id-1', 'chat-id-2'],

      // Listen to events with a specific recipient:
      // recipient: '0x...' (replace with recipient wallet address)
    },
    // Connection options:
    connection: {
      retries: 3, // Retry connection 3 times if it fails
    },
    raw: false, // Receive events in structured format
  }
);

// Chat event listeners:

// Stream connection established:
stream.on(CONSTANTS.STREAM.CONNECT, async (a) => {
  console.log('Stream Connected');

  // Send initial message to PushAI Bot:
  console.log('Sending message to PushAI Bot');

  await userAlice.chat.send(pushAIWalletAddress, {
    content: 'Hello, from Alice',
    type: 'Text',
  });

  console.log('Message sent to PushAI Bot');
});

// Chat message received:
stream.on(CONSTANTS.STREAM.CHAT, (message) => {
  console.log('Encrypted Message Received');
  console.log(message); // Log the message payload
});

// Chat operation received:
stream.on(CONSTANTS.STREAM.CHAT_OPS, (data) => {
  console.log('Chat operation received.');
  console.log(data); // Log the chat operation data
});

// Connect the stream:
await stream.connect(); // Establish the connection after setting up listeners

// Stream disconnection:
stream.on(CONSTANTS.STREAM.DISCONNECT, () => {
  console.log('Stream Disconnected');
});

// Stream Chat also supports other products like CONSTANTS.STREAM.NOTIF.
// For more information, please refer to push.org/docs/notifications.

Stream chat parameters

ParamTypeDefaultRemarks
listenconstant-Choose from various streams: CONSTANTS.STREAM.CHAT, CONSTANTS.STREAM.CHAT_OPS, CONSTANTS.STREAM.NOTIF, CONSTANTS.STREAM.CONNECT, CONSTANTS.STREAM.DISCONNECT
options*PushStreamInitializeProps-Optional configuration properties for initializing the stream.
options.filter*object-Configure to listen to specific chats or notifications.
options.filter.channels*array of strings['*']Pass list of channels over here to only listen to notifications coming from them.
options.filter.chats*array of strings['*']Pass list of chatids over here to only listen to chats coming from them.
options.connection*object-Option to configure the connection settings of the stream
options.connection.retries*number3Number of automatic retries incase of error
options.raw*booleanfalseIf enabled, respond with metadata useful in verifying the integrity of incoming chats or notifications among other things.

Stream chat listen events

Listen eventsWhen is it triggered?
CONSTANTS.STREAM.CHATWhenever a chat is received.
CONSTANTS.STREAM.CHAT_OPSWhenever a chat operation is received.
CONSTANTS.STREAM.CONNECTWhenever the stream establishes connection.
CONSTANTS.STREAM.DISCONNECTWhenever the stream gets disconnected.

For Expected Stream Chat Responses, Visit Push Chat Docs


For Push Spaces

To create a space

// pre-requisite API calls that should be made before
// need to get user and through that encryptedPvtKey of the user
const user = await PushAPI.user.get(account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7', env: 'staging');

// need to decrypt the encryptedPvtKey to pass in the api using helper function
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey(encryptedPGPPrivateKey: user.encryptedPrivateKey, signer: _signer);

// actual api
const response = await PushAPI.space.create({
  spaceName:'wasteful_indigo_warbler',
  spaceDescription: 'boring_emerald_gamefowl',
  listeners: ['0x9e60c47edF21fa5e5Af33347680B3971F2FfD464','0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
  spaceImage: &lt;space image link&gt; ,
  speakers: ['0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
  isPublic: true,
  account: '0xD993eb61B8843439A23741C0A3b5138763aE11a4',
  env: 'staging',
  pgpPrivateKey: pgpDecryptedPvtKey, //decrypted private key
  scheduleAt: new Date("2024-07-15T14:48:00.000Z"),
  scheduleEnd: new Date("2024-07-15T15:48:00.000Z")
});

To create a token gated space

// pre-requisite API calls that should be made before
// need to get user and through that encryptedPvtKey of the user
const user = await PushAPI.user.get(account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7', env: 'staging');

// need to decrypt the encryptedPvtKey to pass in the api using helper function
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey(encryptedPGPPrivateKey: user.encryptedPrivateKey, signer: _signer);

// actual api
const response = await PushAPI.space.create({
  spaceName:'wasteful_indigo_warbler',
  spaceDescription: 'boring_emerald_gamefowl',
  listeners: ['0x9e60c47edF21fa5e5Af33347680B3971F2FfD464','0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
  spaceImage: &lt;space image link&gt; ,
  speakers: ['0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
  rules: {
    'spaceAccess': {
      'conditions': [
        {
          'any': [
            {
              'type': 'PUSH',
              'category': 'ERC20',
              'subcategory': 'holder',
              'data': {
                'contract': 'eip155:5:0x2b9bE9259a4F5Ba6344c1b1c07911539642a2D33',
                'amount': 1000,
                'decimals': 18
              }
            },
            {
              'type': 'GUILD',
              'category': 'guildRoles',
              'subcategory': 'specificRole',
              'data': {
                'guildId': '13468',
                'guildRoleId': '19924'
              }
            }
          ]
        }
      ]
    }
  },
  isPublic: true,
  account: '0xD993eb61B8843439A23741C0A3b5138763aE11a4',
  env: 'staging',
  pgpPrivateKey: pgpDecryptedPvtKey, //decrypted private key
  scheduleAt: new Date("2024-07-15T14:48:00.000Z"),
  scheduleEnd: new Date("2024-07-15T15:48:00.000Z")
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
account_string-user address
spaceName*string-group name
spaceDescription*string-group description
spaceImage*string-group image link
listeners*Array-wallet addresses of all listeners except speakers and spaceCreator
speakers*Array-wallet addresses of all speakers except listeners and spaceCreator
isPublic*boolean-true for public space, false for private space
scheduleAt*Date-Date time when the space is scheduled to start
scheduleEndDate-Date time when the space is scheduled to end
contractAddressERC20 (deprecated)stringnullERC20 Contract Address
numberOfERC20 (deprecated)int0Minimum number of tokens required to join the group
contractAddressNFT (deprecated)stringnullNFT Contract Address
numberOfNFTTokens (deprecated)int0Minimum number of nfts required to join the group
rulesRules-conditions for space access (see format below)
pgpPrivateKeystringnullmandatory for users having pgp keys
envstring'prod'API env - 'prod', 'staging', 'dev'

Rules format

export enum ConditionType {
  PUSH = 'PUSH',
  GUILD = 'GUILD',
}

export type Data = {
  contract?: string;
  amount?: number;
  decimals?: number;
  guildId?: string;
  guildRoleId?: string;
  guildRoleAction?: 'all' | 'any';
  url?: string;
  comparison?: '>' | '<' | '>=' | '<=' | '==' | '!=';
};

export type ConditionBase = {
  type?: ConditionType;
  category?: string;
  subcategory?: string;
  data?: Data;
  access?: Boolean;
};

export type Condition = ConditionBase & {
  any?: ConditionBase[];
  all?: ConditionBase[];
};

export interface Rules {
  entry?: {
    conditions: Array<Condition | ConditionBase>;
  };
  chat?: {
    conditions: Array<Condition | ConditionBase>;
  };
}

To check user access of a token gated space


// actual api
const response = await PushAPI.space.getAccess({
  spaceId:'8f7be0068a677df166c2e5b8a9030fe8a4341807150339e588853c0049df3106',
  did: '0x9e60c47edF21fa5e5Af33347680B3971F2FfD464'
  env: 'staging',
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceIdstring-space address
didstring-user address
envstring'prod'API env - 'prod', 'staging', 'dev'

To update space details

Note - updateSpace is an idompotent call

// pre-requisite API calls that should be made before
// need to get user and through that encryptedPvtKey of the user
const user = await PushAPI.user.get(account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7', env: 'staging');

// need to decrypt the encryptedPvtKey to pass in the api using helper function
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey(encryptedPGPPrivateKey: user.encryptedPrivateKey, signer: _signer);

// actual api
const response = await PushAPI.space.update({
    spaceId: 'spaces:e0553610da88dacac70b406d1222a6881c0bde2c5129e58b526b5ae729d82116',
    spaceName: 'Push Space 3',
    spaceDescription: 'This is the oficial space for Push Protocol',
    listeners: ['0x2e60c47edF21fa5e5A333347680B3971F1FfD456','0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
    spaceImage: &lt;group image link&gt; ,
    speakers: ['0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
	  scheduleAt: '2023-07-15T14:48:00.000Z',
	  scheduleEnd: '2023-07-15T15:48:00.000Z',
    status: PushAPI.ChatStatus.PENDING,
    account: '0xD993eb61B8843439A23741C0A3b5138763aE11a4',
    env: 'staging',
    pgpPrivateKey: pgpDecryptedPvtKey, //decrypted private key
});

To update token gated space details

Note - updateSpace is an idompotent call

// pre-requisite API calls that should be made before
// need to get user and through that encryptedPvtKey of the user
const user = await PushAPI.user.get(account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7', env: 'staging');

// need to decrypt the encryptedPvtKey to pass in the api using helper function
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey(encryptedPGPPrivateKey: user.encryptedPrivateKey, signer: _signer);

// actual api
const response = await PushAPI.space.update({
    spaceId: 'spaces:e0553610da88dacac70b406d1222a6881c0bde2c5129e58b526b5ae729d82116',
    spaceName: 'Push Space 3',
    spaceDescription: 'This is the oficial space for Push Protocol',
    listeners: ['0x2e60c47edF21fa5e5A333347680B3971F1FfD456','0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
    spaceImage: &lt;group image link&gt; ,
    speakers: ['0x3829E53A15856d1846e1b52d3Bdf5839705c29e5'],
	  scheduleAt: '2023-07-15T14:48:00.000Z',
	  scheduleEnd: '2023-07-15T15:48:00.000Z',
    status: PushAPI.ChatStatus.PENDING,
    rules: {
      'entry': {
        'conditions': [
          {
            'any': [
              {
                'type': 'PUSH',
                'category': 'ERC20',
                'subcategory': 'token_holder',
                'data': {
                  'address': 'eip155:5:0x2b9bE9259a4F5Ba6344c1b1c07911539642a2D33',
                  'amount': 1000,
                  'decimals': 18
                }
              },
              {
                'type': 'GUILD',
                'category': 'guildRoles',
                'subcategory': 'allRoles',
                'data': {
                  'guildId': '13468'
                }
              }
            ]
          }
        ]
      },
      'chat': {
        'conditions': [
          {
            'all': [
              {
                'type': 'PUSH',
                'category': 'ERC20',
                'subcategory': 'token_holder',
                'data': {
                  'address': 'eip155:5:0x2b9bE9259a4F5Ba6344c1b1c07911539642a2D33',
                  'amount': 1000,
                  'decimals': 18
                }
              },
              {
                'type': 'GUILD',
                'category': 'guildRoles',
                'subcategory': 'specificRole',
                'data': {
                  'guildId': '13468',
                  'guildRoleId': '19924'
                }
              }
            ]
          }
        ]
      }
    },
    account: '0xD993eb61B8843439A23741C0A3b5138763aE11a4',
    env: 'staging',
    pgpPrivateKey: pgpDecryptedPvtKey, //decrypted private key
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-Id of the space
account*string-user address
spaceName*string-space name
spaceDescription*string-space description
spaceImage*string-space image
status*string-space status - 'ACTIVE', 'PENDING', 'ENDED'
listeners*Array-wallet addresses of all listeners except speakers and spaceCreator
speakers*Array-wallet addresses of all speakers except listeners and spaceCreator
scheduleAt*Date-Date time when the space is scheduled to start
scheduleEndDate-Date time when the space is scheduled to end
contractAddressERC20 (deprecated)stringnullERC20 Contract Address
numberOfERC20 (deprecated)int0Minimum number of tokens required to join the space
contractAddressNFT (deprecated)stringnullNFT Contract Address
numberOfNFTTokens (deprecated)int0Minimum number of nfts required to join the space
rulesRules-conditions for space and chat access (see format above)
pgpPrivateKeystringnullmandatory for users having pgp keys
envstring'prod'API env - 'prod', 'staging', 'dev'

To get space details by spaceId

const response = await PushAPI.space.get({
  spaceId:
    'spaces:108f766a5053e2b985d0843e806f741da5ad754d128aff0710e526eebc127afc',
  env: 'staging',
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
envstring'prod'API env - 'prod', 'staging', 'dev'

To start a space

const response = await PushAPI.space.start({
  spaceId:
    'spaces:108f766a5053e2b985d0843e806f741da5ad754d128aff0710e526eebc127afc',
  env: 'staging',
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
envstring'prod'API env - 'prod', 'staging', 'dev'

To stop a space

const response = await PushAPI.space.stop({
  spaceId:
    'spaces:108f766a5053e2b985d0843e806f741da5ad754d128aff0710e526eebc127afc',
  env: 'staging',
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
envstring'prod'API env - 'prod', 'staging', 'dev'

To approve a space request

const response = await PushAPI.space.approve({
  status: 'Approved',
  account: '0x18C0Ab0809589c423Ac9eb42897258757b6b3d3d',
  senderAddress: '0x873a538254f8162377296326BB3eDDbA7d00F8E9', // spaceId
  env: 'staging',
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
status'Approved''Approved'flag for approving and rejecting space request, supports only approving for now
senderAddress_string-space request sender's address or spaceId of a space
signer*--signer object
pgpPrivateKeystringnullmandatory for users having pgp keys
envstring'prod'API env - 'prod', 'staging', 'dev'

To add listeners to space

const response = await PushAPI.space.addListeners({
  spaceId,
  listeners: [
    `eip155:0x65585D8D2475194A26C0B187e6bED494E5D68d5F`,
    `eip155:0xE99F29C1b2A658a478E7766D5A2bB28322326C45`,
  ],
  signer: signer,
  pgpPrivateKey: pgpDecrpyptedPvtKey,
  env: env as ENV,
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
listenersArray-new listeners that needs to be added to the space. Don't add listeners which are already part of space
envstring'prod'API env - 'prod', 'staging', 'dev'

To remove listeners from space

const response = await PushAPI.space.removeListeners({
  spaceId,
  listeners: [
    `eip155:0xB12869BD3a0F9109222D67ba71e8b109B46908f9`,
    `eip155:0x2E3af36E1aC6EEEA2C0d59E43Be1926aBB9eE0BD`,
  ],
  signer: signer,
  pgpPrivateKey: pgpDecrpyptedPvtKey,
  env: env as ENV,
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
listenersArray-existing listeners that needs to be removed from the space. Don't add listeners which are not part of space
envstring'prod'API env - 'prod', 'staging', 'dev'

To add speakers to space

const response = await PushAPI.space.addSpeakers({
  spaceId,
  listeners: [
    `eip155:0x65585D8D2475194A26C0B187e6bED494E5D68d5F`,
    `eip155:0xE99F29C1b2A658a478E7766D5A2bB28322326C45`,
  ],
  signer: signer,
  pgpPrivateKey: pgpDecrpyptedPvtKey,
  env: env as ENV,
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
speakersArray-new speakers that needs to be added to the space. Don't add speakers which are already part of space
envstring'prod'API env - 'prod', 'staging', 'dev'

To remove speakers from space

const response = await PushAPI.space.removeSpeakers({
  spaceId,
  speakers: [
    `eip155:0xB12869BD3a0F9109222D67ba71e8b109B46908f9`,
    `eip155:0x2E3af36E1aC6EEEA2C0d59E43Be1926aBB9eE0BD`,
  ],
  signer: signer,
  pgpPrivateKey: pgpDecrpyptedPvtKey,
  env: env as ENV,
});

Allowed Options (params with _ are mandatory)

ParamTypeDefaultRemarks
spaceId_string-space id
speakersArray-existing speakers that needs to be removed from the space. Don't add speakers which are not part of space
envstring'prod'API env - 'prod', 'staging', 'dev'

Fetching list of user spaces

const spaces = await PushAPI.space.spaces({
  account: string;
  pgpPrivateKey?: string;
  /**
   * If true, the method will return decrypted message content in response
   */
  toDecrypt?: boolean;
  /**
   * Environment variable
   */
  env?: ENV;
});
ParamTypeDefaultRemarks
accountstring-user address (Partial CAIP)
toDecryptbooleanfalseif "true" the method will return decrypted message content in response
pgpPrivateKeystringnullmandatory for users having pgp keys
envstring'prod'API env - 'prod', 'staging', 'dev'

Example normal user:

// pre-requisite API calls that should be made before
// need to get user and through that encryptedPvtKey of the user
const user = await PushAPI.user.get({
  account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7',
  env: ENV.STAGING,
})

// need to decrypt the encryptedPvtKey to pass in the api using helper function
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey(encryptedPGPPrivateKey: user.encryptedPrivateKey, signer: signer);

// actual api
const spaces = await PushAPI.space.spaces({
    account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7',
    toDecrypt: true,
    pgpPrivateKey: pgpDecryptedPvtKey,
    env: ENV.STAGING,
});

Example NFT user:

// Fetch user
const user = await PushAPI.user.get({
  account: `nft:eip155:${nftChainId}:${nftContractAddress}:${nftTokenId}`,
  env: env as ENV,
});

// Decrypt PGP Key
const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({
  encryptedPGPPrivateKey: user.encryptedPrivateKey,
  signer: nftSigner,
});

// Actual api
const spaces = await PushAPI.space.spaces({
  account: `nft:eip155:${nftChainId}:${nftContractAddress}:${nftTokenId}`,
  toDecrypt: true,
  pgpPrivateKey: pgpDecrpyptedPvtKey,
  env: env as ENV,
});

Fetching list of user space requests

const spaces = await PushAPI.space.requests({
  account: string;
  pgpPrivateKey?: string;
  /**
   * If true, the method will return decrypted message content in response
   */
  toDecrypt?: boolean;
  /**
   * Environment variable
   */
  env?: ENV;
});
ParamTypeDefaultRemarks
accountstring-user address (Partial CAIP)
toDecryptbooleanfalseif "true" the method will return decrypted message content in response
pgpPrivateKeystringnullmandatory for users having pgp keys
envstring'prod'API env - 'prod', 'staging', 'dev'

Example normal user:

// pre-requisite API calls that should be made before
// need to get user and through that encryptedPvtKey of the user
const user = await PushAPI.user.get({
  account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7',
  env: ENV.STAGING,
})

// need to decrypt the encryptedPvtKey to pass in the api using helper function
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey(encryptedPGPPrivateKey: user.encryptedPrivateKey, signer: signer);

// actual api
const spaces = await PushAPI.space.requests({
    account: 'eip155:0xFe6C8E9e25f7bcF374412c5C81B2578aC473C0F7',
    toDecrypt: true,
    pgpPrivateKey: pgpDecryptedPvtKey,
    env: ENV.STAGING,
});

Example NFT user:

// Fetch user
const user = await PushAPI.user.get({
  account: `nft:eip155:${nftChainId}:${nftContractAddress}:${nftTokenId}`,
  env: env as ENV,
});

// Decrypt PGP Key
const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({
  encryptedPGPPrivateKey: user.encryptedPrivateKey,
  signer: nftSigner,
});

// Actual api
const spaces = await PushAPI.space.requests({
  account: `nft:eip155:${nftChainId}:${nftContractAddress}:${nftTokenId}`,
  toDecrypt: true,
  pgpPrivateKey: pgpDecrpyptedPvtKey,
  env: env as ENV,
});

const spaces = await PushAPI.space.trending({
  env?: ENV;
});
ParamTypeDefaultRemarks
envstring'prod'API env - 'prod', 'staging', 'dev'
pagenumber1page index of the results
limitnumber10number of items in 1 page

For Push Video

Initializing User is the first step before proceeding to Initializing Video API. Please refer Manage User Section

data & setData
import { TYPES, CONSTANTS } from '@pushprotocol/restapi';

// 1. For a vanilla JS project
let data: TYPES.VIDEO.DATA = CONSTANTS.VIDEO.INITIAL_DATA;
/*
- fn function is supplied by the caller of setData()
- fn is a function that accepts current 'data' as input and returns updated 'data'
*/
const setData = (fn: (data: TYPES.VIDEO.DATA) => TYPES.VIDEO.DATA): void => {
  /*
    - Here, we are passing the current value of 'data' to fn
    - The return value of fn() i.e., the updated value of 'data' is assigned back to 'data'
  */
  data = fn(data);
};

// 2. For a React project
import { useState } from 'react';
const [data, setData] = useState<TYPES.VIDEO.DATA>(
  CONSTANTS.VIDEO.INITIAL_DATA
);

Stream Video

These APIs enable you to receive incoming video call request and other video events in real time without polling the API. Push Video achieves this by the use of sockets.

import { CONSTANTS, TYPES } from '@pushprotocol/restapi';

// userAlice.initStream(listen, {options?})
// Initial setup
const stream = await userAlice.initStream([CONSTANTS.STREAM.VIDEO], {
  filter: {
    channels: ['*'], // pass in specific channels to only listen to those
    chats: ['*'], // pass in specific chat ids to only listen to those
  },
  connection: {
    retries: 3, // number of retries in case of error
  },
  raw: false, // enable true to show all data
});

// Listen for video events
await stream.on(CONSTANTS.STREAM.VIDEO, (data: TYPES.VIDEO.EVENT) => {
  console.log(data);
});

// Connect stream, Important to setup up listen first
stream.connect();

// stream supports other products as well, such as CONSTANTS.STREAM.NOTIF, CONSTANTS.STREAM.CHAT
// more info can be found at push.org/docs

Stream chat parameters

ParamTypeDefaultRemarks
listenconstant-Choose from various streams: CONSTANTS.STREAM.VIDEO,CONSTANTS.STREAM.CHAT, CONSTANTS.STREAM.CHAT_OPS, CONSTANTS.STREAM.NOTIF, CONSTANTS.STREAM.CONNECT, CONSTANTS.STREAM.DISCONNECT
options*PushStreamInitializeProps-Optional configuration properties for initializing the stream.
options.filter*object-Configure to listen to specific chats or notifications.
options.filter.channels*array of strings['*']Pass list of channels over here to only listen to notifications coming from them.
options.filter.chats*array of strings['*']Pass list of chatids over here to only listen to chats coming from them.
options.connection*object-Option to configure the connection settings of the stream
options.connection.retries*number3Number of automatic retries incase of error
options.raw*booleanfalseIf enabled, respond with metadata useful in verifying the integrity of incoming chats or notifications among other things.

* - Optional

Stream events

Listen eventsWhen is it triggered?
CONSTANTS.STREAM.VIDEOWhenever video call operation is received.
CONSTANTS.STREAM.CHATWhenever a chat is received.
CONSTANTS.STREAM.CHAT_OPSWhenever a chat operation is received.
CONSTANTS.STREAM.CONNECTWhenever the stream establishes connection.
CONSTANTS.STREAM.DISCONNECTWhenever the stream gets disconnected.

For Expected Stream Responses, Visit Push Chat Docs


Initializing Video API

// Initialising the video API
// async initialize(onChange, {options?});
const aliceVideoCall = await userAlice.video.initialize(setData, {
  stream: stream, // pass the stream object created using Stream API, please refer to [Initializing Stream API] to learn how to get this stream object.
  config: {
    video: true, // to enable video on start, for frontend use
    audio: true, // to enable audio on start, for frontend use
  },
  media: MediaStream, // to pass your existing media stream(for backend use)
});

Parameters:

ParamTypeSub-TypeDefaultRemarks
onChangeconstant--Function to update the video call data, takes a function as an argument which receives the latest state of data as a param and should return the modified/new state of data
optionsVideoInitializeOptions--configuration properties for initializing the video.
-options.streamPushStream-Option to configure to enable listening to only certain chats or notifications.
-options.config.video*boolean-pass trueto enable video on start, else pass false.
-options.config.audio*boolean-pass trueto enable audio on start, else pass false.
-options.media*MediaStream-Local stream. For backend use. Defaults to null.

* - Optional

Request a Video Call

// Make a video call request to recipient
// aliceVideoCall.request(recipients[], options?);
await aliceVideoCall.request([recipient]);

Parameters:

ParamTypeSub TypeDescription
recipientsstring[]-Wallet address or addresses of the recipient(s)
options*VideoInitializeOptions--
options.rules.access.typestringIdentifier for Push Video or Space. We use VIDEO_NOTIFICATION_ACCESS_TYPE.PUSH_CHAT from @pushprotocol/restapi here for Push Video
options.rules.access.data.chatId?stringUnique identifier for every push chat, here, the one between the alice and the bob

* - Optional

Approve a incoming video call request

// aliceVideoCall.approve(address?);
await aliceVideoCall.approve();

Parameters:

ParamTypeSub TypeDescription
address*string-Wallet address of the caller, received in stream listener(s)

* - Optional


Reject an incoming video call request

// aliceVideoCall.deny(address?);
await aliceVideoCall.deny();

Parameters:

ParamTypeSub TypeDescription
address*string-Wallet address of the caller, received in stream listener(s)

* - Optional


Disconnect an ongoing video call

// aliceVideoCall.disconnect();
await aliceVideoCall.disconnect();

Manage Media Config

aliceVideoCall.config({
  video: true, // true to enable and false to disable video
  audio: true, // true to enable and false to disable audio
});

Parameters:

PropertyTypeDescription
video*Booleantrue to enable video and false to disable video
audio*Booleantrue to enable audio and false to disable audio

* - Optional


Read current media state

  • data.local.stream will hold the media stream of local video.
  • data.incoming[0].stream will hold the media stream of the peer.
  • data.local.audio will be true if the local user audio is enabled and vice versa.
  • data.local.video will be true if the local user video is enabled and vice versa.
  • data.incoming[0].audio will be true if the remote user audio is enabled and vice versa.
  • data.incoming[0].video will be true if the remote user video is enabled and vice versa.

FAQs

Package last updated on 12 Apr 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc