Skip to content

Latest commit

 

History

History
471 lines (348 loc) · 13.6 KB

File metadata and controls

471 lines (348 loc) · 13.6 KB

import Container from './../../components/Container' import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' import PlatformTabs from '../../components/PlatformTabs' import PlatformTabItem from '../../components/PlatformTabItem' import CloudBanner from '../../components/CloudBanner'

API

Initialization

To setup the client you need to configure it with your projectId which you can obtain from WalletConnect Cloud.

Furthremore you may need to configure the domain and isLimited parameters:

  • domain defaults to window.location.host and must be set to the domain setup in Cloud Setup. For example app.example.com. Do not add the scheme (https://).
  • allApps determines if your app has access to all of the user's subscriptions, or only the ones that the app is hosted on. By setting it to true, it enables setting domain to a value other than window.location.host. Setting allApps: true can be useful during development to allow your localhost-deployed app to access the subscriptions for the domain you setup. Note that most apps do not need to set this in production environments, as they only need access to their own subscriptions. When enabled, the user has to sign a SIWE message granting your app more permissions, and this requires additional consideration from the user. Read here for more details.

<PlatformTabs groupId="w3iw" activeOptions={["react", "javascript"]}

initWeb3inboxClient({ projectId, domain, allApps })

References

  • projectId: Your WalletConnect project ID
  • domain (Optional): Your app's domain. Defaults to window.location.host.
  • allApps (Optional): Set to true to request access to all of the user's notification subscriptions for all apps, instead of only domain. Defaults to false.
const client = await Web3InboxClient.init({ projectId, domain, allApps })

References

  • projectId: Your WalletConnect project ID
  • domain (Optional): Your app's domain. Defaults to window.location.host.
  • allApps (Optional): Set to false to request access to all of the user's notification subscriptions for all apps, instead of only domain. Defaults to true.

Managing Account

Setting account for web3inbox

<PlatformTabs groupId="w3iw" activeOptions={["react", "javascript"]}

const { 
  data: account, 
  isRegistered, 
  identityKey, 
  setAccount,
  error, 
  isLoading,
} = useW3iAccount('eip155:1:0x9A...')

References

  • data: CAIP-10 account currently active in Web3Inbox
  • setAccount: Change actively managed account in Web3Inbox. Does not need to be used as you can set the account directly in the params.
  • isRegistered: A boolean of whether or not the account currently set is registered
  • identityKey: Currently set account's identity key
  • error: A string, representing possible error of setting an account.
  • isLoading: A boolean, representing if an account is being set
await client.setAccount('eip155:1:0x9AfEaC202C837df470b5A145e0EfD6a574B21029')

const account = client.getAccount() // eip155:1:0x9AfEaC202C837df470b5A145e0EfD6a574B21029

client.watchAccount(account => {
  console.log({ account }) // eip155:1:0x9AfEaC202C837df470b5A145e0EfD6a574B21029
})

References

  • account: CAIP-10 account currently active in Web3Inbox
  • setAccount: Change actively managed account in Web3Inbox
  • watchAccount: Watcher ticks whenever the account updates

Registering an account

<PlatformTabs groupId="w3iw" activeOptions={["react", "javascript"]}

import { useSignMessage } from "@wagmi"
const { signMessageAsync } = useSignMessage();

const { isRegistered } = useW3iAccount('eip155:1:0x9A...')

const { prepareRegistration } = usePrepareRegistration()
const { register, isLoading: isRegistering } = useRegister()

const handleRegistration = async () => {
  try {
    const { message, registerParams } = await prepareRegistration();
    const signature = await signMessageAsync({ message: message });
    await register({ registerParams, signature });
  } catch (registerIdentityError: any) {
    console.error(registerIdentityError)
  }
};

References

  • isRegistered: A boolean of whether or not the account currently set is registered
  • prepareRegistration: Prepare registration params
  • register: Register using a signature and register params
  • isLoading: A boolean, representing if an account is being registered

Some suggested methods of signing the message:

import { signMessageAsync } from "@wagmi/core"


const { registerParams, signature } = await client.prepareRegistration({
  account
})
const isRegistered = await client.getAccountIsRegistered(account)
const signature = await signMessageAsync({ message });
await register({ registerParams, signature });

References

  • prepareRegistration: Prepare registration params
  • register: Register using a signature and register params
  • getAccountIsRegistered: Returns if account is registered

Some suggested methods of signing the message:

Managing Subscription

Subscribe, Unsubscribe, Get Subscription, Check if Subscribed.

<PlatformTabs groupId="w3iw" activeOptions={["react", "javascript"]}

const { subscribe, isLoading: isSubscribing } = useSubscribe();
const { unsubscribe, isLoading: isUnsubscribing } = useUnsubscribe();

// get subscription of current user to current dapp
const { data: subscription } = useSubscription();

// subscribe to current dapp
subscribe()

// unsubscribe from current dapp
unsubscribe()

// get all subscriptions for current account
const subscriptions = useSubscriptions()

const isSubscribed = Boolean(subscription)

References

  • account (Optional): CAIP-10 account
  • domain (Optional): dapp domain
  • subscribe: Function to subscribe to current dApp () => void
  • unsubscribe: Function to unsubscribe to current dApp () => void
  • isSubscribed: Reactive state, checking if subscribed to dApp Boolean
  • isSubscribing: If subscribe() is in-progress and has not finished yet
  • isUnsubscribing: If unsubscribe() is in-progress and has not finished yet
  • subscription: Reactive state, returning current subscription information, of type:
{
  topic: string
  account: string
  relay: relayertypes.protocoloptions
  metadata: Metadata
  scope: ScopeMap
  expiry: number
  symkey: string
}
  • subscriptions: Reactive state, returning array of current subscriptions
// check if current account is subscribed to current dapp
const isSubscribed = client.isSubscribedToDapp()

// watch if current account is subscribed to current dapp
client.watchIsSubscribed(isSubbed => console.log({ isSubbed }))

// subscribe to current dapp with current account
await client.subscribeToDapp()

// unsubscribe from current dapp with current account
await client.unsubscribeFromDapp()

// get current account's subscription to current dapp
const subscription = client.getSubscription()

// watch current account's subscription to current dapp
client.watchSubscription(subscription => console.log({ subscription }))

// get current account's subscriptions
const subscriptions = client.getSubscriptions()

// watch current account's subscriptions
client.watchSubscriptions(subscriptions => console.log({ subscriptions }))

References

  • account (Optional): CAIP-10 account
  • domain (Optional): dapp domain
  • subscription: Non-Reactive state, returning current subscription information, of type:
{
  topic: string
  account: string
  relay: relayertypes.protocoloptions
  metadata: Metadata
  scope: ScopeMap
  expiry: number
  symkey: string
}
  • subscription: Non-Reactive state, returning array of current subscriptions

Managing Notifications

Get notifications

<PlatformTabs groupId="w3iw" activeOptions={["react", "javascript"]}

// watch notifications of current account's subscription to current dapp
const notificationsPerPage = 5
const isInfiniteScroll = true
const unreadFirst = true

const { data: notifications, nextPage, markAllReturnedNotificationsAsRead, markNotificationsAsRead } = useNotifications(
  notificationsPerPage, 
  isInfiniteScroll,
  unreadFirst 
)

// marking a single notification as read
notifications[0].markAsRead();

// mark all notifications currently in `notifications` returned array as read
markAllReturnedNotificationsAsRead();

// mark specific notifications as read
markNotificationsAsRead(notifications.slice(2).map(n => n.id))

References

  • notificationsPerPage: Number representing how many notifications to get per fetch
  • isInfiniteScroll: Whether or not to keep already fetched notifications when getting next page
  • unreadFirst: Whether or not unread messages should be sorted at the top, regardless of timestamp
  • notifications: Array of notifications, of type
  • notification.markAsRead: Mark the notification as read
  • markAllReturnedNotificationsAsRead: Mark currently fetched notifications as read. This does not mark all notifications as read, just the ones that have been fetched and returned here..
  • markNotificationsAsRead: Takes an array of notification IDs and marks them as read
{
  title: string;
  sentAt: number;
  body: string;
  id: string;
  isRead: boolean;
  url: string | null;
  type: string;
  markAsRead: () => Promise<void>
}

You can retrieve notifications using pagination. One approach is to provide the last notification's ID as the starting point:

const notificationsPage = client.getNotificationHistory({
  limit: 3,
  // The `id` of the last notification, for example:
  startingAfter: "some-notification-id"
})

const notificationsPerPage = 5
const isInfiniteScroll = true
const unreadFirst = true

let notifications = []

const onUpdate = ({notifications: fetchedNotifications}: GetNotificationsReturn) => {
  notifications = fetchedNotifications
}

const { nextPage, markAllReturnedNotificationsAsRead, markNotificationAsRead } = client.pageNotifications(
  notificationsPerPage,
  isInfiniteScroll,
  unreadFirst,
)(onUpdate)


// marking a single notification as read
notifications[0].markAsRead();

// mark all notifications currently in `notifications` returned array as read
markAllReturnedNotificationsAsRead();

// mark specific notifications as read
markNotificationsAsRead(notifications.slice(2).map(n => n.id))

References

  • notificationsPerPage: Number representing how many notifications to get per fetch
  • isInfiniteScroll: Whether or not to keep already fetched notifications when getting next page
  • unreadFirst: Whether or not unread messages should be sorted at the top, regardless of timestamp
  • onUpdate:: A callback that will be called whenever notifications get updated
  • nextPage:: A function to be called to fetch the next page of notifications
  • notifications: Array of notifications, of type
  • notification.markAsRead: Mark the notification as read
  • markAllReturnedNotificationsAsRead: Mark currently fetched notifications as read. This does not mark all notifications as read, just the ones that have been fetched and returned here..
  • markNotificationsAsRead: Takes an array of notification IDs and marks them as read
{
  title: string;
  sentAt: number;
  body: string;
  id: string;
  isRead: boolean;
  url: string | null;
  type: string;
  markAsRead: () => Promise<void>
}

Notification Types

Manage and fetch notification types.

<PlatformTabs groupId="w3iw" activeOptions={["react", "javascript"]}

const { data: types, update} = useNotificationTypes()

References

  • update: (enabledScopeNames: string[]) -> void
  • types: Map of scopes (Notification types)
type ScopeMap = Record<
  string,
  {
    name: string
    description: string
    enabled: boolean
  }
>
// get scopes of current account's subscription to current dapp
const types = client.getNotificationTypes()

// watch scopes of specific account's subscription to specific dapp
client.watchNotificationTypes(scp => { console.log(scp) })

client.update(["enabledType-1", "enabledType-2"])

References

  • update: (enabledScopeNames: string[]) -> void
  • types: Map of scopes (Notification types)
type ScopeMap = Record<
  string,
  {
    name: string
    description: string
    enabled: boolean
  }
>