Introduction
In the fast-evolving world of blockchain technology, on-chain alerts are critical in keeping users informed about various events and actions occurring on the blockchain.
These notifications provide users with important updates, alerts, and confirmations on their transactions,
smart contracts, and interactions with the blockchain.
On-chain notifications are a powerful tool that can be used to send messages to users on the Celo blockchain.
These notifications can be used to inform users of important events, such as a transaction being sent or a new smart contract being deployed.
On-chain notifications can also be used to provide users with updates on the status of their transactions or smart contracts.
In this article, we will show you how to use Mailchain to send on-chain notifications on Celo. We will also discuss the benefits of using Mailchain for on-chain notifications.
Overview of Mailchain
Mailchain is a decentralized messaging protocol used to send on-chain notifications. It ensures end-to-end encryption by default, and guarantees the security and privacy of messages sent on-chain.
With Mailchain, developers can effortlessly send messages to blockchain addresses on different protocols, simplifying their communication needs.
The Mailchain SDK is the recommended integration method, as it handles the intricacies of working with the REST API, including tasks like signing, verifying, encrypting, and decrypting messages.
By leveraging Mailchain, developers can focus on building their applications without worrying about the complexities of blockchain communication.
Prerequisites
To follow along, below is a list of things you need to do:
-
Download and install NodeJS.
-
Create a new Mailchain account for development and testing.
-
Register an Ethereum address in Mailchain to your dev and test account.
-
Sign in or create a Tenderly account.
-
Create an Ngrok account and install Ngrok on your machine.
Ngrok is a tool used for exposing your local development environment to the internet, making it accessible for webhooks and testing.
Creating a Tenderly Account
To use Tenderly Alerting to listen for events on the blockchain and send real-time notifications to your Mailchain account, follow these steps to create a Tenderly account:
-
Visit the Tenderly website
-
Click on the "Sign Up" button located in the top right corner of the Tenderly homepage. You will be directed to the account registration page.
-
Provide your details and complete the registration process.
-
Check your email inbox for a verification email from Tenderly. Click on the verification link provided in the email to verify your account and activate it.
Installing Ngrok
To install Ngrok and set it up to expose your local development environment to the internet, follow these steps:
-
Sign up for an account on Ngrok’s website if you haven’t already. Once signed in, navigate to the "Download" section.
-
Choose the appropriate version compatible with your OS (Operating System) and download the installation package.
-
Once the download is complete, extract the installation package and locate the installation package and extract its contents to the directory of your choice.
-
Set up Ngrok authentication to get your authentication token. In
your Ngrok account dashboard, locate your authentication token, and copy
it.
- Open a terminal or command prompt and navigate to the directory
where you extracted the Ngrok installation package.
6 . In the terminal, enter the following command and replace
`<YOUR_AUTH_TOKEN>` with the authentication token you copied.
$ ngrok config add-authtoken \<YOUR_AUTH_TOKEN\>
This command authenticates your Ngrok installation with your account.
- To start Ngrok and expose your local development environment, use
the following command:
$ ngrok http 80
By following these steps, you can install and set up Ngrok to expose your local development environment to the Internet. This allows you to test webhooks and access your application from external services, facilitating the integration of on-chain notifications with Mailchain.
Creating a Celo Wallet
To interact with the Celo blockchain, you'll need a Celo wallet. There are several options available, including the Celo Wallet mobile app or a hardware wallet like Ledger.
-
Install the Metamask browser extension on your preferred web browser
-
Once the installation is complete, you will see the MetaMask iconadded to your browser's toolbar. Click on the MetaMask icon toopen the extension.
-
Accept the terms of use: MetaMask will present you with the terms of use and privacy policy. Read through the information and click "Accept" to continue.
-
Create a new MetaMask wallet: You will be prompted to either import an existing wallet or create a new one. Choose the option to "Create a Wallet."
-
Set a strong password: Enter a secure password for your MetaMask wallet. Make sure to choose a password that is unique and not easily guessable. Confirm the password to proceed.
-
Save your secret backup phrase: MetaMask will generate a secret backup phrase consisting of 12 or 24 words. This backup phrase is crucial for recovering your wallet in case of loss or device change. Write down the backup phrase and store it in a safe and secure location.
-
Verify your backup phrase
-
Connect to the Celo network. ChainId.network is an index of all EVM-compatible chains.
Celo is also EVM-compatible so connect your wallet, search for Celo, and click on Add Chain “Celo Mainnet” to automatically add Celo Mainnet to your Metamask browser wallet.
Creating a Tenderly Webhook
To set up a webhook in Tenderly and make it accessible through your local development environment, follow these steps:
Step 1 - Set up the Express JS API Service
- Open your terminal or command prompt and create a new directory for the webhook implementation.
mkdir mailchain-tenderly-example\
cd mailchain-tenderly-example
- Create a new file called `server.js` in the current directory using the following command.
ni touch server.js
- Open the `server.js` file in a text editor and paste the provided code into it. The code sets up an Express JS API service to handle the webhook events. This code is based on code provided in Tenderly's webhook configuration page under Advanced Options.
// server.js
//
// Use this sample code to handle webhook events
// 1) Paste this code into a new file (server.js)
//
// 2) npm init
//
// 3) Install dependencies
// npm install --save express
// npm install --save crypto
//
// 4) Run the server on http://localhost:8008
// npm start (start script in package.json must point to server.js)
const express = require('express');
const crypto = require('crypto');
const app = express();
// replace this with key taken from dashboard for specific webhook
// if you are testing webhook before creation set it on empty string
const signingKey = '';
app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
const signature = request.headers['x-tenderly-signature'];
const timestamp = request.headers['date'];
if (!isValidSignature(signature, request.body, timestamp)) {
response.status(400).send('Webhook signature not valid');
return;
}
let body;
try {
body = JSON.parse(request.body.toString());
} catch(e) {
response.status(400).send('Webhook error: ', e);
return;
}
const eventType = body.event_type;
switch (eventType) {
case 'TEST':
// Then define and call a function to handle the test event
break;
case 'ALERT':
// Then define and call a function to handle the alert event
break;
// ... handle other event types
default:
console.log('Unhandled event type ', eventType);
}
// Return a 200 response
response.send();
});
const port = 8008;
app.listen(port, () => console.log('Running on port ', port));
function isValidSignature(signature, body, timestamp) {
const hmac = crypto.createHmac("sha256", signingKey); // Create a HMAC SHA256 hash using the signing key
hmac.update(body.toString(), 'utf8'); // Update the hash with the request body using utf8
hmac.update(timestamp); // Update the hash with the request timestamp
const digest = hmac.digest("hex");
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest));
}
- Initialize npm by running this command
npm init
-
You can accept all the defaults, but make sure the entry point is server.js.
-
In the terminal, run the following command to install the required dependencies (Express and Crypto):
npm install --save express
npm install --save crypto
- Run the command below to start the Express server on port 8008.
npm start
- Verify that the server is running by checking the terminal output,
indicating that the server is listening on port 8008.
Step 2 - Make the Local Webhook Publicly Accessible
Since we are running the tutorial in a local environment, we need to make our webhook accessible to Tenderly, which is not possible directly on the local network. To achieve this, we can use Ngrok to enable external access to our webhook. Alternatively, you can use your solution or browser-based development environments like Gitpod.
To make our local webhook accessible, follow these steps:
-
Open a new terminal or command prompt window separate from the one running the Express server.
-
In the new terminal window, run the following command to start Ngrok and expose your local development environment
ngrok http 8008
Ngrok will create a secure tunnel and provide a temporary public URL for
accessing your local webhook.
-
After starting Ngrok, it will display a Forwarding URL in the terminal output. The URL will look something like `https://012a-93-12-152-21.ngrok-free.app`. Copy this URL as it will serve as the publicly accessible endpoint for your webhook.
-
Leave the Ngrok service running in the terminal window. If you close Ngrok, the Forwarding URL will change, and you will need to update the webhook configuration in Tenderly accordingly.
Remember that when using Ngrok, the publicly accessible URL is temporary and will change every time you start Ngrok. Therefore, you may need to update the webhook configuration in Tenderly each time you restart Ngrok.
By following these steps and keeping Ngrok running, you can make your local webhook accessible to Tenderly through the provided Forwarding URL. This allows Tenderly to send webhook events to your locally running server, enabling you to receive and process notifications from Tenderly in your development environment.
Step 3 - Configure Tenderly Webhook Destination and Alert
Now that we have a publicly accessible destination endpoint for our webhook, we can configure Tenderly to send notifications to that endpoint. Follow these steps:
- Open your web browser and navigate to your Tenderly Dashboard.
-
Choose Alerts > Destinations: In the Tenderly Dashboard, navigate to the Alerts section and select "Destinations." If this is your first time using Tenderly, or have you haven't set up any destinations yet. You may need to add a wallet address to monitor.
-
In the "Add Destination" section, choose "Webhook" as the destination type.
-
Enter the details for your webhook, including the Ngrok URL with the correct endpoint. Attach “/webhook” to your forwarding url. For example, enter `https://805e-105-113-12-84.ngrok-free.app/webhook\` as the Webhook URL.
-
Click the "Send test webhook" button to test the webhook configuration. If the test is successful, you will see a confirmation message. Click "Add webhook" to save the webhook configuration.
- In the "Active Destinations" section, locate the destination you just created and click the button for more details. Copy the Signing Secret that is provided. We will need it in the next section to store this secret in a secure and private location.
By following these steps, you have configured Tenderly to send notifications to your webhook destination. You have also tested the webhook to ensure it is functioning correctly.
Remember to copy the provided Signing Secret and keep it secure, as we will use it in the next section to verify the authenticity of the webhook requests.
Step 4 - Configure Environment Variables and Start the Application
To securely store sensitive information and configure settings for our application, we will utilize environment variables. These variables hold values that are passed to the server-side code. Follow the steps below to set up the environment variables:
- In the root folder of your application, create or edit the `.gitignore` file. Add the following snippet to ensure that existing environment files are ignored by Git and prevent their changes from being stored:
# ENV
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
- If the `.env.development.local` file does not exist in your root directory, create it. Otherwise, open it in your code editor and add the following values:
# Your environment
ENVIRONMENT="development"
# Tenderly
TENDERLY_SIGNING_KEY="xxxxx"
WEBHOOK_SENDER_ADDRESS="username@mailchain.com"
WEBHOOK_RECIPIENT_ADDRESS="username@mailchain.com"
# Mailchain
SECRET_RECOVERY_PHRASE="your secret recovery phrase"
Ensure that you replace `"xxxxx"` with your actual Tenderly signing key, and `"your secret recovery phrase"` with your Mailchain secret recovery phrase for your development account. Additionally, set the `WEBHOOK_SENDER_ADDRESS` and `WEBHOOK_RECIPIENT_ADDRESS` to the desired Mailchain addresses.
- Open your terminal and run the following command to install the `dotenv` package:
npm install --save dotenv
- Open the `server.js` file and insert the following lines at the beginning, above the line `const express = require('express');`.
require('dotenv').config({ path: `.env.${process.env.ENVIRONMENT || 'development'}.local` });
This code ensures that the environment variables from the corresponding environment file (e.g., `.env.development.local`) are loaded correctly.
- Locate the line `const signingKey = '';` in the `server.js` file and replace it with the following code:
const signingKey = process.env.TENDERLY_SIGNING_KEY;
This line configures the signing key from the environment variable specified in `.env.development.local`.
By following these steps, you have configured the necessary environment variables for your application. The sensitive information and settings are now securely stored, allowing our application to access them as needed.
Step 5 - Install Mailchain SDK and Configure Webhook
To integrate Mailchain functionality into our webhook, we need to install the Mailchain SDK and configure it accordingly. Follow the steps below:
- In your terminal, run the following command to install the Mailchain SDK package:
npm install --save @mailchain/sdk
- Inside the `server.js` file, locate the line `const app = express();` and add the following code snippet below it:
const { Mailchain } = require('@mailchain/sdk');
const mailchain = Mailchain.fromSecretRecoveryPhrase(process.env.SECRET_RECOVERY_PHRASE);
This code imports the Mailchain SDK package and configures it using the
secret recovery phrase provided in the environment variable
`SECRET_RECOVERY_PHRASE`.
- Within the existing `switch` statement in the `app.post('/webhook', express.raw.…)` route, add the following code block under the `case 'TEST':` section:
const { data, error } = await mailchain.sendMail({
from: process.env.WEBHOOK_SENDER_ADDRESS,
to: [process.env.WEBHOOK_RECIPIENT_ADDRESS],
subject: 'Webhook Test',
content: {
text: `The webhook body:\n${JSON.stringify(body, null, 2)}`,
html: `<p>The webhook body:</p><pre>${JSON.stringify(body, null, 2)}</pre>`,
},
});
if (error) {
throw new Error('Mailchain error', { cause: error });
}
This code uses the `mailchain.sendMail()` function to send a test email. You can modify the `subject` and `content` fields to customize the email body based on your requirements. In a production environment, you would typically adjust the message content based on the information received from contract events or transactions.
- To ensure the `async` functionality works correctly, add the `async` keyword to the route handler function. Modify the following line:
app.post('/webhook', express.raw({ type: 'application/json' }), async (request, response) => {
This modification allows us to use `await` within the route
handler function.
By following these steps, you have installed the Mailchain SDK, configured it using the secret recovery phrase, and implemented the Mailchain functionality within the webhook. The webhook will send test emails using Mailchain when Tenderly triggers the TEST event.
Step 6 - Testing the Webhook; Sending A Mail With Mailchain
To ensure that the webhook is functioning correctly, follow these steps:
-
Relaunch the Application and make sure the webhook is active.
-
Ensure that Ngrok is still running and has provided a public endpoint for your webhook.
-
Check that Tenderly is configured to send alerts to the Ngrok URL, which will route them to your webhook's endpoint.
-
Go to the Tenderly Dashboard and navigate to Alerts > Destinations.
-
Choose the webhook you created earlier from the list of destinations.
-
Click on the 'Test Webhook' button.
- Configure Test Parameters: In the Test Webhook dialog, select the following options:
- Network: Mainnet
- Tx hash:
0x94f27cd0775d14c05455d3348fd7b0ef66f164706faf11eeb6b27a588345ff97
Trigger the Test: Click on the 'Test Webhook' button to trigger
the test.
Check Mailchain Inbox: Finally, check your Mailchain Inbox for the test
message.
By following these steps, you can verify if the webhook is properly receiving events from Tenderly and sending notifications via Mailchain.
It is important to note that as of the time of writing, Tenderly does not support the Celo blockchain. Therefore, the steps and instructions provided in this article may not be directly applicable to monitoring events or transactions on the Celo network using Tenderly.
However, the methodology and concepts discussed in this article remain relevant and can be applied to other blockchain networks supported by Tenderly.
The general process of setting up webhooks, configuring endpoints, and handling events can be adapted to different blockchain platforms once Tenderly extends its support to Celo.
Keep an eye on Tenderly's official announcements and updates to stay informed about their plans to include support for the Celo blockchain.
Once Tenderly adds Celo support, you can leverage the knowledge gained from this article to set up webhooks and monitor events on the Celo network using Tenderly’s platform.
Do stay updated with Tenderly’s official communication channels for any news regarding Celo support, as
their expansion to new networks is an ongoing process.
Conclusion
Congratulations! You have successfully built a webhook that can send alerts whenever specific events occur on the blockchain or in transaction logs.
This webhook provides valuable functionality for various use cases, such as monitoring balance changes, issuing user receipts for NFT purchases, sending welcome messages, notifying your team of failed transactions, and providing upcoming expiry or liquidation notices, among others.
Remember to exercise caution and disable the webhook in your Tenderly account when you have finished using it to ensure that alerts are no longer sent.
By implementing this webhook, you have taken a significant step towards enhancing your application’s real-time notifications and improving user experience. Feel free to explore further customization and integration possibilities to meet your specific requirements.
The code used in this article can be found in this git repository
Next Step
Mailchain is not the only notification infrastructure provider in Web3. You can also try out Alchemy, Push Protocol, EPNS, or even Moralis.
About the Author
John Fawole is a blockchain technical writer and Solidity developer; connect with him on LinkedIn.