arrow_back

Adding Decentralized Notifications to an Application using Push Protocol

ログイン 参加
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

Adding Decentralized Notifications to an Application using Push Protocol

Lab 1時間 universal_currency_alt クレジット: 5 show_chart 中級
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

GSP1163

Google Cloud self-paced labs logo

Overview

Push Protocol is the most widely adopted web3 communication middleware, providing technical solutions for fully decentralized communication. Push allows applications, smart contracts, backends, and protocols to communicate on-chain and off-chain through wallet addresses in a multi-chain, gasless, and permission-less manner.

In this lab, you will walk through the process of adding decentralized notifications to your BigQuery-based application.

Important: we strongly advise you to use a test wallet address for this lab (one with none of your crypto assets stored). You will be sharing your private key inside of the lab environment and we cannot guarantee the security of your private key or any assets associated with it.

Objectives

In this lab, you will:

  • Set up a channel for users to receive push notifications
  • Send notifications to enable direct communications among users using Push SDK
Note: You will need to have a MetaMask crypto wallet for this lab. While we provide instructions for setting up MetaMask, you can use any other wallet that supports the Ethereum test network.

Setup and Requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

Set up MetaMask

  1. If you haven't set up MetaMask already, go to MetaMask.io and click the Download button, which will take you to the relevant page to download the extension based on the browser you’re using.

  2. Open the MetaMask extension and click on Get Started.

  3. If you have an existing wallet, you can import it using the seed phrase or simply create a new one.

  4. Follow the rest of the setup process to create your MetaMask wallet. Once it has been properly set up, you can now access your wallet by clicking on the MetaMask icon at the top-right-end corner of your browser.

Task 1. Create Channel on Push Protocol

Creating a channel is the very first step for sending notifications via Push. Having a channel on Push dApp (and smart contracts) allows you to establish a communication pathway with your users in Web3.0.

If you don't already have a Channel, you must create one first.

  1. Head to the Push Staging dapp for creating channel.
Note: For this demo we will be creating channel on testnet which does not require any real funds. One can also use Push Prod App to create channel on mainnet, which requires real funds.
  1. Connect your Metamask wallet or any other supported wallet.

Connect Wallet

Note: It is advised to use Metamask wallet to follow along easily. Feel free to use any other wallet.
  1. Once Connected, go to the Developers > Create Channel. Add deatils related to channel such as Channel name, description, website URL and click on the next button. You can use the following details for this demo:
  • Channel Name: Google BigQuery Channel
  • Network: Ethereum Goerli
  • Channel Description: Sending Notifications using Google BigQuery
  • Channel Website URL: https://push.org

Create Channel

Note: Network can be selected as any of the support alias chains which enables multi-chain communication. For this demo it is advised to set it as Ethereum Goerli which enables sending notifications of Ethereum testnet. Note: Time Bound option is an advanced feature which allows to destruct a channel after a specific period of time. It is advised to keep this off for simplification of the demo.
  1. Upload a channel logo and click on next button.

Upload Channel Logo

  1. Click on Create channel button
Note: This step requires some testnet Eth and 50 testnet Push tokens. Faucets are already built in the dapp for getting funds. Feel free to use any other testnet faucet such as Alchemy Faucet, Quicknode Faucet, POW Faucet.

Create Channel

  1. Sign the transactions asked by wallet.

Approval of PUSH tokens - This transaction ensures that your wallet address has successfully approved the EPNSCore contract to use 50 PUSH tokens on your behalf.

Channel Creation on EPNSCore - Once approved, the 2nd transaction calls the channel creation function on EPNSCore smart contract to create the channel.

  1. After successful executions of transactions, channel dashboard should be visible, allowing sending notifications on Push Protocol.

Channel Dashboard

Task 2. Use the client library to fetch data.

Now, ssh into the VM and run the commands to fetch data from Bigquery database using the client library.

SSH into the VM

  1. From the Navigation Menu, under the Compute Engine section, click VM Instances.
  2. On the same row as lab-server, click SSH to open a ssh window and run the following commands.
mkdir push-google-bigquery cd push-google-bigquery curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash source ~/.bashrc nvm install node npm init touch server.js
  1. Open the package.json file and replace the content with the following code:
{ "name": "push", "type": "module", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "start": "node server.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@google-cloud/bigquery": "^6.2.0", "@pushprotocol/restapi": "^1.3.8", "ethers": "^5.7.2" } }

To query data from the BigQuery database, you'll need to install the BigQuery client library using npm. This library provides a range of tools and features that make it easy to work with BigQuery and retrieve data from your database.

  1. To install the BigQuery client library, run the following command in the Cloud Shell:
npm install @google-cloud/bigquery

The SQL query used below fetches the hash and gas price of a transaction from a public BigQuery database.

Note: A public dataset is used for this task. Feel free to use any other dataset or create your own dataset.
  1. Open the server.js file and replace the content with the following code:
// Imports the Google Cloud client library import { BigQuery } from "@google-cloud/bigquery"; // Queries a public Blockchain dataset. async function queryData() { // Creates a client const bigqueryClient = new BigQuery(); // The SQL query to run to select the value of Bitcoin const sqlQuery = `SELECT \`hash\`, gas_price FROM \`bigquery-public-data.crypto_ethereum.transactions\` WHERE DATE(block_timestamp) = "2023-04-24" LIMIT 10`; const options = { query: sqlQuery, // Location must match that of the dataset(s) referenced in the query. location: "US", }; console.log("Rows:"); // Run the query const [rows] = await bigqueryClient.query(options); for (const row of rows) { console.log(row); await sendNotification(row); } } queryData(); const sendNotification = async (data) => { // TODO : Task 2 };
  1. Run the above script mentioned in server.js file to query the data using the following command in SSH.
npm start

Expected Sample Output:

The expected output contains the queried data in JSON format according to the sqlQuery made to the database. The below output consists of 2 properties:

hash - The transaction hash

gas_price - Gas price of the transaction

{ hash: '0xb4f9089b4c60308b6756692de2ea596a61b59c28dc09c18c91ac49be1c03cfcd', gas_price: 46287777808 } { hash: '0xec170acf0940f1ce2db863d6824462e6c94bb44003f78aeb091580a534d77c40', gas_price: 46287777808 } { hash: '0xfdd184d1e15eb0e86f6ca3385805aa27c6a1ff22898d21692ca8c130f55d4685', gas_price: 46287777808 } { hash: '0x352dd2dd80abb22ce2d411b6a862fae2b3d6bc59f9e3d58fd1cbead9fa472a33', gas_price: 46281777808 } ... ...

Click Check my progress to verify the objective.

Fetch data from Bigquery database using the client library.

The data to be sent as a notification is now ready. There are different ways to send notifications out. You can find more details from the Push SDK here.

Push SDK

You are now all set to start sending the notifications.

Task 3. Sending notifications using Javascript

In this section you'll learn how to send notifications using the Push SDK.

Retrieve your Metamask private key

  1. Click on the identicon in the top right.

  2. Select the account you'd like to export.

  3. On the account page, click on the menu (three dots) in the upper right corner, and then on the Account Details button.

  4. Click Export Private Key.

To access your private key, you'll now need to enter your wallet password. Once you've done so, click Confirm to proceed.

Your private key will now be revealed. Click to copy it, and save it somewhere safe.

Note: we aren't showing it in the below screenshot for obvious reasons -- but yours will be there.
  1. Click Done to close the screen.
Important: Private key of wallet MUST NOT be shared with anyone. To ensure that the private key remains secure, it's important to keep it confidential and not share it with anyone. One way to do this is to store the private key as part of a .env file. This file is typically used to store sensitive information like API keys, passwords, and other confidential data that should not be shared publicly.

Send notifications

Now you will need to install the Push Protocol REST API and ethers library in the project directory. @pushprotocol/restapi allows developers to send notifications by communicating with Push Nodes. In addition to the Push Protocol REST API, ethers library consists of various functions which can be used for interacting with the Ethereum Blockchain and its ecosystem.

  1. Run the following command in the SSH to install the libraries:
npm install @pushprotocol/restapi@latest ethers

Now you will import PushAPI from restapi package in server.js file and use the PushAPI.payloads.sendNotification function to send notifications. More details about the function can be found in the Push Documentation.

  1. Add the following import statements to the top of the server.js file:
import * as PushAPI from "@pushprotocol/restapi"; import * as ethers from "ethers"; const PK = 'your_channel_address_secret_key'; // channel private key const Pkey = `0x${PK}`; const _signer = new ethers.Wallet(Pkey);
  1. Next, add the following code to the sendNotification function in server.js file. Replace <your wallet/channel address> with your wallet address.
Note: There are multiple ways of sending notifications. Learn more about different ways of sending messages here. const sendNotification = async (data) => { try { const apiResponse = await PushAPI.payloads.sendNotification({ signer: _signer, type: 1, // broadcast- sends notifications to everyone's who has opt-in identityType: 2, // direct payload notification: { title: `[SDK-TEST] notification TITLE:`, body: `[sdk-test] notification BODY` }, payload: { title: `Blockchain data`, body: `Gas Price for Trx ${data.hash} was ${data.gas_price} wei`, //taken from above example cta: '', //any relevant link you want them to click img: '' //any relevant image for better UX }, channel: 'eip155:5:<your wallet/channel address>', // your channel address env: 'staging' }); } catch (err) { console.error('Error: ', err); } } sendNotification();
  1. Run the above script mentioned in server.js file to send notifications.
npm start
  1. Navigate to the Push Protocol dashboard and click on the Inbox tab. You should see the blockchain data notifications that you just sent!

Notifications sent

Click Check my progress to verify the objective.

Sending notifications using Javascript.

Receiving notifications is a critical component as it make or breaks the user experience. You can use Push extension/ Push App for users to receive notifications, or simply integrate these notifications into your own platform such as any dApp, Mobile App, Wallet Extension or Web 2.5 platforms like creating a Telegram, Twitter, Email, Discord bots, etc.

Additionally, you can leverage BigQuery data by adding functionalities like chat, video chat, screen sharing, etc. A concrete example of it would be adding a help desk, customer care and a chat section for better sharing of BigQuery data. Learn about Push Chat here.

Congratulations!

Congratulations! In this lab, you learned how to use BigQuery to query blockchain data and send notifications using Push Protocol. You're all set to take the user experience of your dApp to the next level using BigQuery and Push Protocol. The complete source code for this tutorial can be found in the Google BigQuery Demo GitHub repository.

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated: July 8, 2023

Lab Last Tested: July 8, 2023

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.