Vivek Suthar

VS

Real-Time Push Notifications for Solana: Enhancing User Engagement with On-Chain Webhooks

Introduction:

Building a consumer app that engages users with real-time on-chain events is a daunting challenge for any developer. The complexity of managing Android and iOS configurations, setting up webhook servers, and handling notifications for on-chain activities involves a hefty amount of work. From managing indexers and parsers to maintaining databases, setting up a reliable notification system for blockchain events can feel overwhelming.

Even in the current ecosystem, only a few mobile apps like Phantom, Backpack, and Solflare attempt to offer notifications for blockchain events, and even those are often unreliable(at least for me). Building your own notifications server from scratch becomes a massive task for a developer.

But here’s the good news: the landscape has evolved. Today, many RPC providers offer webhook services that deliver on-chain events directly to your server, allowing you to process and customize notifications to keep your users engaged seamlessly, no more struggling to manage complex infrastructure. Now you can focus on delivering a top-notch user experience with real-time updates on Solana.

So let’s dive in and build a Real-Time Notifications Server that keeps your users informed about on-chain events using Helius Webhooks, Firebase Cloud Messaging, and a Push Notification Service.

What We’re Going to Build:

We’ll create a simple app where users can subscribe to specific on-chain events or general topics of interest. Whenever something happens on-chain, our backend will process these events in real time and send push notifications directly to the user’s device. Here’s a breakdown of what we’ll be working on:

  • Mobile App: A user-friendly interface where users can subscribe to specific on-chain events (like token transfers or contract interactions) or general notifications.

  • Webhook Backend: A webhook server powered by Helius that listens to Solana events in real time, processes them, and triggers notifications.

  • Push Notification Service: We’ll use Firebase Cloud Messaging (FCM) to send push notifications to user's mobile devices, ensuring they stay up to date with on-chain activities as they happen.

By the end, we will have a fully functional notifications system, giving your users real-time updates without the hassle of building everything from scratch. Let’s code it.

Prerequisites :

  1. React Native Development Setup:

  2. Basic Understanding of the Solana Ecosystem:

Setting up Firebase for Push Notifications.

So Let’s First set up Firebase Cloud messaging and download some important files.

  • Add your project name, allow the default setting, and click on Create project. Wait till your project is being created.

Once the project is created, you should see a screen like this.

Now, Let’s register our Android App, Click on the Android icon, which will open a page.

Enter the package name, but remember this name as we will require this while building our app.

After adding the package name, you can leave optional fields, then you will be prompted to download the google-services.json file. Download this file and keep it, we will need this in the next step where we will build the app.

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727251420857/e21812ef-44d9-415f-b1dc-081c5698fc43.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727251420857/e21812ef-44d9-415f-b1dc-081c5698fc43.png align="left")

After downloading the file, click on Next and continue, skip Firebase SDK and in the last click go to the console.

Now Click on the Settings icon at top-left, Select project settings, and go to settings

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727251890325/cbb82a3f-1d63-40be-baf8-ea844de2d273.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727251890325/cbb82a3f-1d63-40be-baf8-ea844de2d273.png align="left")

Now Here, Go to the Service account and you will see a screen like this

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727252030463/539dd256-b0df-4502-a1ba-dddc59ca8871.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727252030463/539dd256-b0df-4502-a1ba-dddc59ca8871.png align="left")

From Here, Select NodeJS and Click on Generate new Private key, it will download a service account.json file, keep this file as we will need it while building our backend file. I am referring to this file as solnoti.json

So At this point, we are done with the Firebase project config.
Make sure you have both google-services.json and solnoti.json file.

Setting up Helius WebHooks.

  • Once logged in go to the WebHooks section

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727255893736/db05f1d1-0456-46b4-9188-514a0c696842.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727255893736/db05f1d1-0456-46b4-9188-514a0c696842.png align="left")

and click on New Webhook.

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727255916649/358d7bc9-355e-4afa-a07b-915bfc466247.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727255916649/358d7bc9-355e-4afa-a07b-915bfc466247.png align="left")

Now fill up the details, As of now we want to set our webhook on devnet,

Select the Webhook type as enhanced so we get the enhanced data, not the raw data. From the Transaction types, Select Any, So it will deliver every transaction to us and later we can decide which transaction to parse and process.

Now the thing you notice is WebHook Url, as our server is running on localhost how do we make a URL for it?

Don’t worry, it’s super easy, We will use the localhost.run to test our backend. (You can also use ngrok)

Now open another terminal and run

1ssh -R 80:localhost:3000 nokey@localhost.run

This command establishes an SSH reverse tunnel, forwarding traffic from port 80 on the localhost.run server to port 3000 on your local machine. The -R flag is used to create the reverse tunnel, allowing external users to access your local server running on port 3000 by connecting to localhost.run port 80. The nokey@localhost.run part specifies the remote server (localhost.run) and user (nokey), with no SSH key required for the connection.

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727271686536/a02530cf-c90c-4872-bdc6-924cb04e0c63.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727271686536/a02530cf-c90c-4872-bdc6-924cb04e0c63.png align="left")

Something is shown above. Copy that URL and paste that URL into the Webhook URL field.

Now in the account address, add your wallet address so we can have onchain events from that wallet. Hit Confirm, and now our webhook is ready.

Keep this URL and Webhook ID as we need them in later steps.

Setting up Backend Server:

Open the terminal and run

1mkdir solana-notification-backend 2bun init -y . 3bun install express body-parser @types/express firebase-admin

This will create a new directory, initialize a new Bun project, and add required dependencies like Express and firebase-admin.

Breakdown of Dependencies:

  • express: A web framework for Node.js to handle HTTP requests.

  • body-parser: Middleware for parsing incoming request bodies.

  • @types/express: TypeScript definitions for Express.

  • firebase-admin: Firebase Admin SDK for server-side Firebase interactions.

Now, Remember the services-account.json we downloaded, paste it into the project root, and rename it to solnoti.json

Now create a lib folder and inside it create the below files and paste the below code.

firebaseadmin.ts

1import admin from "firebase-admin"; 2 3import serviceAccount from "../solnoti.json"; 4 5admin.initializeApp({ 6 credential: admin.credential.cert(serviceAccount as never), 7}); 8 9export default admin;

Explanation:

  • Imports: The code imports the Firebase Admin SDK and the service account credentials from a JSON file (typically generated from the Firebase console).

  • Initialization: The admin.initializeApp() function is called with the service account credentials, allowing the application to authenticate and interact with Firebase services securely.

  • Export: The initialized admin instance is exported, making it available for use in other parts of the application, such as sending notifications or accessing Firestore.

processNotification.ts

1 2import sendNotification, { 3 type SendNotificationOptions, 4} from "./sendNotification"; 5import { getFCMToken } from "../db"; 6 7type NativeTransfer = { 8 amount: number; 9 fromUserAccount: string; 10 toUserAccount: string; 11}; 12 13type ProcessTransferNotificationKey = { 14 feePayer: string; 15 signature: string; 16 amount: number; 17 nativeTransfers: NativeTransfer[]; 18}; 19 20export default async function processTransferNotification( 21 options: ProcessTransferNotificationKey, 22) { 23 const transfers = options.nativeTransfers; 24 for (const transfer of transfers) { 25 await sendTransferNotifications(transfer); 26 } 27} 28 29async function sendTransferNotifications( 30 transfer: NativeTransfer, 31): Promise<void> { 32 const sendNotificationForSender = 33 await buildNotificationMessageForSender(transfer); 34 35 const sendNotificationForReceiver = 36 await buildNotificationMessageForReceiver(transfer); 37 38 if (sendNotificationForSender) { 39 await sendNotification(sendNotificationForSender); 40 } 41 42 if (sendNotificationForReceiver) { 43 await sendNotification(sendNotificationForReceiver); 44 } 45} 46 47async function buildNotificationMessageForSender( 48 transfer: NativeTransfer, 49): Promise<SendNotificationOptions | null> { 50 const sendFromPubKey = transfer.fromUserAccount; 51 const fromUserFCMToken = await getFCMToken(sendFromPubKey); 52 53 if (fromUserFCMToken) { 54 const amountSent = transfer.amount / 1000000000; 55 const to = transfer.toUserAccount; 56 57 return { 58 title: `You sent ${amountSent} SOL`, 59 fcmToken: fromUserFCMToken, 60 image: undefined, 61 body: `You successfully sent ${amountSent} SOL to ${to}.`, 62 }; 63 } 64 65 return null; 66} 67 68async function buildNotificationMessageForReceiver( 69 transfer: NativeTransfer, 70): Promise<SendNotificationOptions | null> { 71 const sentToPubKey = transfer.toUserAccount; 72 const toUserFCMToken = await getFCMToken(sentToPubKey); 73 74 if (toUserFCMToken) { 75 const amountReceived = transfer.amount / 1000000000; 76 const from = transfer.fromUserAccount; 77 78 return { 79 title: `You received ${amountReceived} SOL`, 80 fcmToken: toUserFCMToken, 81 image: undefined, 82 body: `${from} sent you ${amountReceived} SOL.`, 83 }; 84 } 85 86 return null; 87}

sendNotification.ts

1import admin from "./firebaseadmin"; 2 3export type SendNotificationOptions = { 4 fcmToken: string; 5 title: string; 6 body: string; 7 image: string | undefined; 8}; 9 10export default function sendNotification(options: SendNotificationOptions) { 11 return admin.messaging().send({ 12 token: options.fcmToken, 13 notification: { 14 body: options.body, 15 title: options.title, 16 imageUrl: options?.image, 17 }, 18 }); 19}

This function accepts SendNotificationOptions as its parameter and uses the Firebase Admin SDK's messaging().send() method to send a notification to the specified device:

  • It sets the target device using the fcmToken.

  • It constructs the notification payload with the provided title, body, and optional image.

addAddressToWebHook.ts

1const HELIUS_API_KEY = process.env.HELIUS_API_KEY; 2const ADDRESS_LISTENER_WEBHOOK_ID = process.env.WEBHOOK_ID; 3const WEBHOOK_POST_URL = "URL_RETRIVED_IN_PREVIOUS_STEP"; 4if (!ADDRESS_LISTENER_WEBHOOK_ID || !HELIUS_API_KEY) { 5 console.log("HELIUS_API_KEY or ADDRESS_LISTENER_WEBHOOK_ID not set"); 6 process.exit(1); 7} 8const getWebhookByID = async (webhookId: string) => { 9 try { 10 const response = await fetch( 11 `https://api.helius.xyz/v0/webhooks/${webhookId}?api-key=${HELIUS_API_KEY}`, 12 { 13 method: "GET", 14 headers: { 15 "Content-Type": "application/json", 16 }, 17 }, 18 ); 19 const data = await response.json(); 20 return data; 21 } catch (e) { 22 console.error("error", e); 23 } 24}; 25const addAddressToWebHook = async (address: string) => { 26 try { 27 const existing = await getWebhookByID(ADDRESS_LISTENER_WEBHOOK_ID); 28 console.log("existing address", existing.accountAddresses); 29 30 const response = await fetch( 31 `https://api.helius.xyz/v0/webhooks/${ADDRESS_LISTENER_WEBHOOK_ID}?api-key=${HELIUS_API_KEY}`, 32 { 33 method: "PUT", 34 headers: { 35 "Content-Type": "application/json", 36 }, 37 body: JSON.stringify({ 38 webhookURL: WEBHOOK_POST_URL, 39 webhookType: "enhancedDevnet", 40 transactionTypes: ["Any"], 41 accountAddresses: [...existing.accountAddresses, address], 42 }), 43 }, 44 ); 45 const data = await response.json(); 46 console.log("Subscribed :", address); 47 } catch (e) { 48 throw e; 49 } 50}; 51 52export default addAddressToWebHook;

Breakdown:

  • Environment Variables:

    • HELIUS_API_KEY and ADDRESS_LISTENER_WEBHOOK_ID are retrieved from the environment variables to be used in API requests.

    • If either of them is not set, the program logs a message and exits.

  • getWebhookByID Function:

    • This function takes webhookId as a parameter and fetches webhook details by requesting the Helius API.

    • The response is returned as JSON.

    • If an error occurs during the request, it catches the error and logs it.

  • addAddressToWebHook Function:

    • This function is designed to add a Solana account address to an existing webhook.

    • It first fetches the existing webhook using getWebhookByID, retrieving the current list of accountAddresses.

    • The new address is appended to the list of existing addresses.

    • A PUT request is made to the Helius API to update the webhook with the new accountAddresses list.

    • If successful, it logs a message confirming that the address has been subscribed.

    • If an error occurs, it throws the error.

  • WEBHOOK_POST_URL Placeholder:

    • WEBHOOK_POST_URL is currently set as a placeholder string ("URL_RETRIVED_IN_PREVIOUS_STEP") and should be updated with the actual URL where webhook events will be posted.

processWebHook.ts

1import type { Request, Response } from "express"; 2import { storeFCMToken } from "../db"; 3import processTransferNotification from "../lib/processNotification"; 4 5export default async function processWebHook(req: Request, res: Response) { 6 const data = req.body; 7 if (data?.length > 0 && data[0] && data[0].type === "TRANSFER") { 8 console.log("Processing SOl TRANSFER Noti", data); 9 processTransferNotification(data[0]); 10 console.log("Processed SOl TRANSFER Noti", data); 11 } 12 res.sendStatus(200); 13}
  • This is just a route handler for our webhook whenever there is an onchain activity for an address, Helius will deliver the data here by making a POST request.

registerTokenForAddress.ts

1import type { Request, Response } from "express"; 2import { storeFCMToken } from "../db"; 3import addAddressToWebHook from "../lib/addAddressToWebHook"; 4 5export default async function registerTokenForAddress( 6 req: Request, 7 res: Response, 8) { 9 try { 10 const { address, token } = req.body; 11 12 if (!address || !token) { 13 return res.status(400).json({ 14 error: "Address and token are required", 15 }); 16 } 17 await addAddressToWebHook(address); 18 await storeFCMToken(address, token); 19 res.status(200).json({ 20 message: "Registered", 21 }); 22 } catch (error: any) { 23 console.log(error); 24 res.status(500).json({ 25 error: "Internal server error", 26 }); 27 } 28}
  • This handler registers an address and its associated Firebase Cloud Messaging (FCM) token.

  • It first extracts the address and token from the request body and check if both are provided. If they are missing, it returns 400 Bad Request error.

  • If valid, it adds the address to a webhook listener using the addAddressToWebHook function, allowing the system to track transactions related to that address.

  • It then stores the FCM token in the database via storeFCMToken. If all operations are successful, it responds with a 200 OK status; otherwise, it catches and logs any errors, returning a 500 Internal Server Error in case of failures.

Now In our root project, Let’s create db.ts a file that will handle our database.

Note that I am here using bun:sqlite as my database, but you can use any of the databases. (Ex Postgres, MongoDB, MySQL)

1import { Database } from "bun:sqlite"; 2 3const db = new Database("fcm_tokens.db"); 4 5db.run(` 6 CREATE TABLE IF NOT EXISTS fcm_tokens ( 7 address TEXT PRIMARY KEY, 8 token TEXT NOT NULL, 9 created_at DATETIME DEFAULT CURRENT_TIMESTAMP, 10 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP 11 ) 12`); 13 14export async function storeFCMToken( 15 address: string, 16 token: string, 17): Promise<void> { 18 const query = ` 19 INSERT INTO fcm_tokens (address, token, updated_at) 20 VALUES (?, ?, CURRENT_TIMESTAMP) 21 ON CONFLICT(address) 22 DO UPDATE SET 23 token = excluded.token, 24 updated_at = CURRENT_TIMESTAMP 25 `; 26 27 db.run(query, [address, token]); 28} 29 30export async function getFCMToken(address: string): Promise<string | null> { 31 const result = db 32 .prepare("SELECT token FROM fcm_tokens WHERE address = ?") 33 .get(address) as { token: string } | null; 34 return result ? result.token : null; 35}

Here, We

  • Initializes a SQLite database using Bun with a file named fcm_tokens.db.

  • Creates a table fcm_tokens with the following fields:

    • address (Primary key)

    • token (Non-null)

    • created_at (Timestamp, default: current time)

    • updated_at (Timestamp, default: current time)

  • storeFCMToken function:

    • Inserts or updates an FCM token for a given address.

    • If the address already exists, it updates the token and updated_at timestamp.

  • getFCMToken function:

    • Fetches the FCM token for a given address from the database.

    • Returns the token or null if not found.

Now inside index.ts paste below code

1import type { Request, Response } from "express"; 2import bodyParser from "body-parser"; 3import express from "express"; 4import admin from "./lib/firebaseadmin"; 5import registerTokenForAddress from "./routes/registerTokenForAddress"; 6import processWebHook from "./routes/processWebhook"; 7 8const app = express(); 9 10const PORT = 8080; 11 12app.use(express.json()); 13 14app.post("/", processWebHook); 15 16app.post("/registerTokenForAddress", registerTokenForAddress); 17 18app.listen(PORT, () => { 19 console.log(`Notification Server is running on port ${PORT}`); 20});

Breakdown of the Code:

  • Imports necessary modules: express, body-parser, and custom modules firebaseadmin, registerTokenForAddress, and processWebHook.

  • Initializes an Express application (app) with the server running on port 8080.

  • Uses express.json() middleware to parse incoming JSON payloads.

  • Defines two POST routes:

    • "/": Handles webhook events via processWebHook.

    • "/registerTokenForAddress": Registers an FCM token for a blockchain address using registerTokenForAddress.

  • Starts the server and logs a message indicating it's running on the specified port (8080).

So, At this point our backend server is ready, Now we have to register our backend service to Helius webhooks so It can deliver the onchain events to us. Let’s do it.

Now, Just Open a terminal and run.

1bun run --watch ./index.ts

This will start our backend server on port 8080

Building Mobile App

Open your terminal and run the below command.

1npx create-expo-app solnoti

It will create a new fresh expo app. Now open the project with your code editor.

Open the terminal and run the below command.

1npm install @react-native-firebase/app @react-native-firebase/messaging

This will install Firebase for react native which we will use to setup native push notifications

Now just paste the google-services.json file in the project root.

Now open app.json and add the below code inside android field

1 "android": { 2 "adaptiveIcon": { 3 "foregroundImage": "./assets/images/adaptive-icon.png", 4 "backgroundColor": "#ffffff" 5 }, 6 "googleServicesFile": "./google-services.json", 7 "package": "com.buildtest.solnoti" 8 },

Here, Replace the package name with your name which you entered in the Firebase config step.

Now inside the plugins field, paste the below content:

1 "plugins": [ 2 "expo-router", 3 "@react-native-firebase/app" 4 ],

This will set up the native config for us so we don’t have to deal with complex configs.

Now open the app/(tabs)/index.tsx file.

Inside it, paste the below code.

1import React, { useState } from 'react'; 2import { 3 StyleSheet, 4 View, 5 Text, 6 TextInput, 7 TouchableOpacity, 8 PermissionsAndroid, 9 ActivityIndicator, 10 Alert, 11} from 'react-native'; 12import messaging from "@react-native-firebase/messaging"; 13import { LinearGradient } from 'expo-linear-gradient'; 14 15const COLORS = { 16 primary: '#9945FF', 17 secondary: '#14F195', 18 background: '#121212', 19 cardBg: '#1C1C1C', 20 text: '#FFFFFF', 21 textSecondary: '#A1A1A1', 22 error: '#FF6B6B', 23}; 24 25async function getFCMTokenFromFirebase() { 26 try { 27 await messaging().requestPermission(); 28 await messaging().registerDeviceForRemoteMessages(); 29 const notificationToken = await messaging().getToken(); 30 console.log("Token", notificationToken); 31 return notificationToken; 32 } catch (error) { 33 throw new Error("Failed to get token"); 34 } 35} 36 37async function registerTokenWithAddress(address: string, token: string) { 38 try { 39//Here, you have to update the URL with your Backend Server URL. 40 const response = await fetch('<http://192.168.1.4:8080/registerTokenForAddress', { 41 method: 'POST', 42 headers: { 43 'Content-Type': 'application/json', 44 }, 45 body: JSON.stringify({ address, token }), 46 }); 47 48 if (!response.ok) throw new Error('Registration failed'); 49 return await response.json(); 50 } catch (error) { 51 console.log(error) 52 throw new Error('Failed to register token'); 53 } 54} 55 56export default function HomeScreen() { 57 const [address, setAddress] = useState(''); 58 const [loading, setLoading] = useState(false); 59 const [registered, setRegistered] = useState(false); 60 const [token, setToken] = useState(''); 61 62 const requestPermission = async () => { 63 try { 64 const granted = await PermissionsAndroid.request( 65 PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS 66 ); 67 if (granted === PermissionsAndroid.RESULTS.GRANTED) { 68 Alert.alert('Success', 'Notification permissions granted!'); 69 } 70 } catch (error) { 71 Alert.alert('Error', 'Failed to request permission'); 72 } 73 }; 74 75 const handleRegistration = async () => { 76 if (!address) { 77 Alert.alert('Error', 'Please enter a valid address'); 78 return; 79 } 80 81 setLoading(true); 82 try { 83 const fcmToken = await getFCMTokenFromFirebase(); 84 await registerTokenWithAddress(address, fcmToken); 85 setToken(fcmToken); 86 setRegistered(true); 87 Alert.alert('Success', 'Successfully registered for notifications!'); 88 } catch (error) { 89 Alert.alert('Error', 'Failed to register token'); 90 } finally { 91 setLoading(false); 92 } 93 }; 94 95 return ( 96 <LinearGradient 97 colors={[COLORS.background, '#2C1F4A']} 98 style={styles.container} 99 start={{ x: 0, y: 0 }} 100 end={{ x: 1, y: 1 }} 101 > 102 <View style={styles.card}> 103 <Text style={styles.title}>Notification Registration</Text> 104 105 <View style={styles.inputContainer}> 106 <Text style={styles.label}>Wallet Address</Text> 107 <TextInput 108 style={styles.input} 109 placeholder="Enter your address" 110 placeholderTextColor={COLORS.textSecondary} 111 value={address} 112 onChangeText={setAddress} 113 /> 114 </View> 115 116 <TouchableOpacity 117 style={styles.permissionButton} 118 onPress={requestPermission} 119 > 120 <LinearGradient 121 colors={[COLORS.secondary + '20', COLORS.secondary + '40']} 122 style={styles.buttonGradient} 123 start={{ x: 0, y: 0 }} 124 end={{ x: 1, y: 0 }} 125 > 126 <Text style={styles.buttonText}>Enable Notifications</Text> 127 </LinearGradient> 128 </TouchableOpacity> 129 130 <TouchableOpacity 131 style={[styles.registerButton, loading && styles.disabledButton]} 132 onPress={handleRegistration} 133 disabled={loading} 134 > 135 <LinearGradient 136 colors={[COLORS.primary, '#7B2FFF']} 137 style={styles.buttonGradient} 138 start={{ x: 0, y: 0 }} 139 end={{ x: 1, y: 0 }} 140 > 141 {loading ? ( 142 <ActivityIndicator color={COLORS.text} /> 143 ) : ( 144 <Text style={styles.buttonText}>Register Device</Text> 145 )} 146 </LinearGradient> 147 </TouchableOpacity> 148 149 {registered && ( 150 <View style={styles.successContainer}> 151 <Text style={styles.successText}>🎉 Successfully Registered!</Text> 152 </View> 153 )} 154 </View> 155 </LinearGradient> 156 ); 157} 158 159const styles = StyleSheet.create({ 160 container: { 161 flex: 1, 162 padding: 16, 163 }, 164 card: { 165 backgroundColor: COLORS.cardBg, 166 borderRadius: 20, 167 padding: 24, 168 marginTop: 40, 169 shadowColor: COLORS.primary, 170 shadowOffset: { 171 width: 0, 172 height: 4, 173 }, 174 shadowOpacity: 0.3, 175 shadowRadius: 8, 176 elevation: 5, 177 }, 178 title: { 179 fontSize: 24, 180 fontWeight: 'bold', 181 color: COLORS.text, 182 marginBottom: 24, 183 textAlign: 'center', 184 }, 185 inputContainer: { 186 marginBottom: 20, 187 }, 188 label: { 189 color: COLORS.textSecondary, 190 marginBottom: 8, 191 fontSize: 16, 192 }, 193 input: { 194 backgroundColor: '#2A2A2A', 195 borderRadius: 12, 196 padding: 16, 197 color: COLORS.text, 198 fontSize: 16, 199 borderWidth: 1, 200 borderColor: COLORS.primary + '40', 201 }, 202 permissionButton: { 203 borderRadius: 12, 204 marginBottom: 16, 205 overflow: 'hidden', 206 }, 207 registerButton: { 208 borderRadius: 12, 209 overflow: 'hidden', 210 }, 211 buttonGradient: { 212 padding: 16, 213 alignItems: 'center', 214 }, 215 disabledButton: { 216 opacity: 0.6, 217 }, 218 buttonText: { 219 color: COLORS.text, 220 fontSize: 16, 221 fontWeight: '600', 222 }, 223 successContainer: { 224 marginTop: 24, 225 alignItems: 'center', 226 }, 227 successText: { 228 color: COLORS.secondary, 229 fontSize: 18, 230 fontWeight: '600', 231 marginBottom: 8, 232 }, 233 tokenText: { 234 color: COLORS.textSecondary, 235 fontSize: 14, 236 paddingHorizontal: 20, 237 }, 238});

Code Walkthrough:

  • State Management: First we define necessary states, like

    • address: Stores the user's wallet address input.

    • loading: Tracks the loading state during registration.

    • registered: A boolean to indicate if registration is successful.

    • token: Stores the generated FCM (Firebase Cloud Messaging) token after registration.

  • Permissions:

    • The requestPermission function requests the user for permission to send notifications using Android's PermissionsAndroid. If granted, an alert shows success.
  • FCM Token Retrieval:

    • The getFCMTokenFromFirebase Function uses Firebase Messaging to request permission, register the device for remote notifications, and retrieve the FCM token.

    • This token is necessary for sending push notifications to the device.

  • Backend Registration:

    • The registerTokenWithAddress function sends the user's address and the FCM token to the backend server (provided as a URL), which stores this information.

    • It uses fetch to send a POST request with the wallet address and token in the body.

  • Handle Registration:

    • The handleRegistration function combines these tasks:

      • It validates the user input (wallet address).

      • It calls getFCMTokenFromFirebase to retrieve the FCM token.

      • It sends the wallet address and token to the backend using. registerTokenWithAddress.

      • It displays appropriate success or error alerts based on the result.

  • User Feedback:

    • Displays a loading spinner while the registration process is ongoing.

    • Shows a success message and registered state once the registration is complete.

So our app is set now. Let’s run it and grab a token to test. Run the below command in your terminal.

1 npx expo run:android

This will build our app and make sure you connect your physical device, as the FCM doesn’t work in emulators.

Once the app is built, it will open the app on your device.

The app will look like this.

First, click on enable notifications. It will prompt for permission to send notifications, allow it.

![https://cdn.hashnode.com/res/hashnode/image/upload/v1728295999422/32b23ffe-69bc-44f7-a961-7788515c24d2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1728295999422/32b23ffe-69bc-44f7-a961-7788515c24d2.png align="left")

So now, Our app has notification permissions set.

Now, Go to the app, Paste a Wallet address that you want to watch, and hit register, you should see registration is successful.

Now Open the wallet and do a SOL transfer from or to the address you added on devnet. You will see a notification on your device.

See I got the notification as soon as I did the transaction.

![https://cdn.hashnode.com/res/hashnode/image/upload/v1727271823973/33e9ef9e-8fa6-4bd8-b97e-4e60367f1089.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1727271823973/33e9ef9e-8fa6-4bd8-b97e-4e60367f1089.png align="left")

At this point, our notification server is up and running, processing notifications for SOL transfers. But the functionality is not limited to this. You can easily extend the server to handle various other on-chain activities, such as SPL token transfers, NFT sales, or even arbitrary transactions. All you need to do is parse the transaction, extract the necessary data, and send notifications to the appropriate user’s device based on their FCM token.

Extending Beyond SOL Transfers:

  • SPL Transfers: Capture token-specific transfers and notify users when they receive or send SPL tokens.

  • NFT Sales: Notify users about successful NFT sales, new listings, or bids on their assets.

  • Arbitrary Transactions: Process any kind of transaction on the Solana, extract relevant details, and push real-time notifications.

By parsing the transactions and extracting the relevant data, you can tailor notifications to fit different use cases, ensuring users are always informed and engaged.

Real-World Token Management:

For this demo, we used a basic sqlite db to simplify the implementation. However, in a real-world scenario, you wouldn’t use a static FCM token for each user. Instead, you need to:

  1. Set Up a Database: Create a database to store the FCM tokens for all users. Each user’s device token should be saved and updated whenever a new token is generated (e.g. when the user reinstalls the app).

  2. Fetch Tokens from Database: Modify your getFCMToken function to query the database and retrieve the correct FCM token for each user before sending notifications.

  3. Caching for Performance: Implement a caching layer to reduce database lookups and speed up token retrieval. This is especially important when handling large-scale notifications, ensuring faster responses and better performance.

Also, this demo is mainly focused on Android, but don’t worry, the iOS config is also the same you have to download one extra file for Apple, add it to the iOS config, and build the app, adding a few lines in the backend and you will have it working.

Conclusion

By now, you should have a solid understanding of how to set up event listeners for on-chain Solana events and engage users with real-time notifications. The tools and techniques discussed here empower you to keep your users informed and excited about the latest on-chain activities. So, what are you waiting for? Go build the next disruptive dApp that will onboard the next million users into Web3 and ultimately bring billions to the decentralized future.

If you get stuck at any point or need more advanced content on Solana X Mobile Development, feel free to reach out!

Let's Connect

By sharing this blog, you're not only helping others discover valuable insights but also contributing to building a supportive community of learners and developers. Plus, you never know who might benefit from the information shared here, just like I did many times. If you find this helpful, leave a reaction to encourage more knowledge-sharing!

Here are my socials in case you'd like to connect with me :

Thank you for being part of this journey. Until next time, keep coding, keep debugging, and keep building amazing things!

You can find the code here:

Backend: https://github.com/VIVEK-SUTHAR/solana-notification-backend

App: https://github.com/VIVEK-SUTHAR/solana-notifications-app