
Before you begin
- Labs create a Google Cloud project and resources for a fixed time
- Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
- On the top left of your screen, click Start lab to begin
Configure OAuth Consent Screen and Create OAuth Client ID
/ 20
Clone Application Repository
/ 20
Add Private Key
/ 20
Deploy W3bstream Applet
/ 10
Configure the Web App
/ 10
Add the Yoga Sesion (with OAuth Playground)
/ 10
Run and Test the Web App
/ 10
W3bstream is a decentralized network that allows IoT devices and other data sources to stream and process data, serving as a bridge between real-world data sources and the blockchain. Through it, data like steps, locations, and achieved fitness goals, can be easily streamed and processed to prove real world activities to blockchain contracts. This enables developers to craft gamified experiences using blockchain - healthy behaviors can be incentivised by rewarding users with NFTs or ERC20 tokens.
In this lab you will learn how to channel Google Fit data via W3bstream to develop decentralized applications (dApps) that mint crypto assets based on user fitness activities. This lab is ideal for developers interested in building applications that bridge the worlds of Web2 and Web3, combining the strengths of Web2 services with the advantages of Web3 incentives.
The application workflow can be summarized as follows:
diagram of app synch process
Please do the following BEFORE you click the Start Lab button!
Metamask Browser Plugin: Install the Metamask browser plugin, which allows you to interact with blockchain networks. Set up an account and configure Metamask to interact with the IoTeX Testnet Blockchain
Fund your Metamask wallet with some test IOTX tokens by claiming them from the IoTeX public faucet. If you want more, you can log in to the IoTeX Developer Portal and claim them from your personal dashboard (you can refer to this article for step-by-step instructions on how to configure Metamask and claim test tokens).
To Add IoTeX Network Testnet network manually in Metamask wallet, use the below details:
Network Name | IoTeX Network Testnet |
---|---|
New RPC URL | https://babel-api.testnet.iotex.io |
Chain ID | 4690 |
Currency Symbol | IOTX |
Now you're ready to click Start lab.
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 Qwiklabs 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:
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab.
Note: If you are using a Pixelbook, open an Incognito window to run this lab.
A Windows VM is being provisioned for this lab, so it will take few minutes for the lab to be ready.
To access the Windows VM, click on the Open Windows VM button from Lab Details panel. Use either PowerShell or Visual Studio Code to perform the tasks for this lab.
For this lab, use the temporaroy Google Account that has been provisioned for you as a student. Use this as both the developer account to access the Google Fit API and as the end user account to generate some fitness data and mint the NFT to our wallet.
Allow Google OAuth Client to get access to the Fitness REST API. Follow these steps to obtain a GOOGLE_ID (Client ID) and a GOOGLE_SECRET (Client secret).
Go to the Google API Console.
Select your project
From the Navigation menu choose APIs & Services > Library.
Search for Fitness API and click the MANAGE button.
In the navigation menu of Fitness API, choose Credentials.
Click Create credentials, then select OAuth Client ID.
If it asks you to CONFIGURE CONSENT SCREEN, follow the configuration:
Select User type: Internal.
Click on CREATE.
Enter app name.
User support email and Developer contact information can be the one of the lab test credentials.
Click SAVE AND CONTINUE.
Click on ADD OR REMOVE SCOPES.
Under Manually add scopes add https://www.googleapis.com/auth/fitness.activity.write
and then click on ADD TO TABLE.
Click on UPDATE.
Click on SAVE AND CONTINUE two times.
Click on BACK TO DASHBOARD.
Click on Credentials > Create credentials, then select OAuth Client ID.
Under Application type, select Web application.
Under Authorized JavaScript origins, add https://developers.google.com
.
Under Authorized redirect URI, enter the URL of the site where responses will be handled and add http://localhost:3000/api/auth/callback/google
.
Click Create. Your new OAuth 2.0 Client ID and secret appear in the list of IDs for your project. An OAuth 2.0 Client ID is a string of characters, something like this:
780816631155-gbvyo1o7r2pn95qc4ei9d61io4uh48hl.apps.googleusercontent.com
Click Check my progress to verify the objective.
Click Check my progress to verify the objective.
nft
folder and add your developer wallet PRIVATE_KEY to this file:The provided account will be used to pay Bundlr fees with testnet tokens. Bundlr is a decentralized storage solution that you will use to store the NFT images. The Bundlr fee can be paid using MATIC tokens, so make sure that the corresponding account has some test MATIC tokens by using one of the following links: https://testmatic.vercel.app/ or https://mumbaifaucet.com (make sure you select the MUMBAI Testnet).
Network Name | Mumbai Testnet |
---|---|
New RPC URL | https://rpc-mumbai.maticvigil.com |
Chain ID | 80001 |
Currency Symbol | MATIC |
Block Explorer URL | https://polygonscan.com/ |
You'll find the generated NFT URI's nft/uploads.json
which you'll need in the next step.
.env.template
:SBT_URI
and REWARDS_URI
variables in the .env
file as per your set up with the values generated in the Get your NFT ready step. Find them in the nft/uploads.json file.OPERATOR_ADDRESS
will be obtained in the next step.npm i
command in the directory.Click Check my progress to verify the objective.
AssemblyScript
code by running:applet/wsproject.json
as the Project file and applet/build/release.wasm
as the Wasm file.Click Check my progress to verify the objective.
blockchain
directory and update the Operator_Address from the previous step in your .env
file with your W3bstream Operator Address.npm i
command in the directory.adapter
directory:.env.local
and populate it with the variables from .env.template
..
NEXTAUTH_SECRET
can be acquired in Vercel secret generator
HTTP_ROUTE
under Event Sources:.env.local
with required values. NEXTAUTH_URL
use http://localhost:3000 as address.Click Check my progress to verify the objective.
PUT
method with the following url: https://www.googleapis.com/fitness/v1/users/me/sessions/1
Click Check my progress to verify the objective.
Navigate to localhost:3000
in your web browser.
Follow the on-screen instructions to register your device and claim your SBT:
Click Check my progress to verify the objective.
Some of the more relevant components of your application:
You start with the user authentication handled by the NextAuth library in auth/[...nextauth].ts, where you establish secure user sessions using Google as the identity provider. This forms the basis for secure interactions throughout the application.
This file sets up Google OAuth authentication for a Next.js application using the NextAuth.js library. The key components of the setup are the providers and callbacks within the authOptions object. The providers array contains the Google provider, configured with necessary details such as clientId, clientSecret, and the scope of authorization required from Google's API, which in this case includes basic profile information and read access to Google Fit data.
The callbacks object contains two methods: jwt and session. The jwt callback intercepts the JSON Web Token (JWT) after authentication, and if an account is authenticated, it assigns the access token from the account to the token object. The session callback is called whenever a session is accessed, and it adds the access token to the session object.
Finally, the authOptions object is passed to the NextAuth function and exported as the default from this module. This setup process allows the Next.js application to handle user authentication via Google, and have access to the user's access token in both the JWT and the session for further authenticated requests to Google's APIs.
Following this, you have the device registration process in register/route.ts, which registers the user's device on a blockchain network for unique identification, further enhancing our application's security.
This file is for registering devices on a blockchain using the DeviceRegistry contract. It imports necessary modules and contract details from a deployments file, and creates a representation of the contract using the getContract function.
The registerDevice function handles the device registration process. It first checks if a device is already registered. If not, it simulates a contract operation to register the device, writes this transaction to the blockchain using walletClient.writeContract, and waits for the transaction to be confirmed.
The isRegistered function checks if a device is already registered by reading from the DeviceRegistry contract. If any errors occur during this process, it logs the error and returns false.
With the foundation laid, you look at pull-data/route.ts, where the application interacts with Google's Fit API, pulling and processing fitness data for a specific device. The processed data is then uploaded to a W3bstream, marking a key step in our application's data flow.
This file processes fitness data from Google Fit for a specific device. The POST function extracts a deviceId from the request, obtains an access token, and processes the device's fitness data. The processDevice function fetches the fitness sessions from Google Fit, processes the data to extract valid points, and uploads the data to W3bstream. The fetchFitSessions function makes a GET request to Google Fit's endpoint to fetch fitness data, and googleAxiosInstance returns an Axios instance configured for Google Fit's API.
Next, you delve into client.ts under services/w3bstream, which manages the actual data upload to the W3bstream, enabling the application to persist and retrieve fitness data.
This TypeScript file manages the upload of fitness data to W3bstream. The uploadFitSessionToWS function checks if there's any fitness data to send, and if so, it prepares a POST request with the device ID and the data, and sends it to a specified HTTP route. The sendRequest function is used to execute the fetch request, and if any errors occur during the process, they are logged and re-thrown.
Finally, you conclude with the frontend code in CollectButton.tsx, a user-facing React component. It interacts with a rewards contract on the blockchain, allowing users to collect rewards for their fitness activities, tying the whole application together in a user-centric manner.
This component is used for interacting with a rewards contract on a blockchain. It uses hooks from the wagmi library to prepare and execute a contract write operation, and to wait for the transaction's confirmation.
The usePrepareContractWrite
hook prepares the contract write operation to call the mintFromAllowance function of the rewards contract with the provided tokenId as an argument.
The useContractWrite
hook executes the contract write operation when the write function is called, which is triggered by a click event on the button.
The useWaitForTransaction hook waits for the transaction's confirmation.
The button is disabled while the write operation is being prepared, is in progress, or while waiting for the transaction confirmation. Feedback is given to the user through the text displayed below the button, indicating whether the transaction is being prepared, is in progress, or has been successful. The transaction data is displayed when the transaction has been successful.
Together, these components form the core of our application, managing everything from user authentication, device registration, data retrieval and processing, to enabling users to receive on-chain rewards for their fitness activities.
You've successfully navigated through a complex landscape of code, learned to integrate the Google Fit API, gamify decentralized applications based on real-world behaviors, set up a W3bstream project, and mint crypto assets.
These skills are not just isolated techniques. They form a holistic approach to building modern, user-centric, and engaging applications. You have learned how to pull real-world data from Google Fit, process it, and use it within a decentralized application to promote healthy behaviors. You've also set up a W3bstream project and used it as a platform for storing and managing fitness data.
Were you intrigued by W3bstream and how to use it to build decentralized applications on real world data? Remember that integrating with a cloud solution is only one of the multiple ways of building real world based applications with W3bstream. These other tutorials will help you keep up your progress:
...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 Date: November 14, 2023
Lab Last Tested Date: September 20, 2023
Copyright 2022 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.
This content is not currently available
We will notify you via email when it becomes available
Great!
We will contact you via email if it becomes available
One lab at a time
Confirm to end all existing labs and start this one