With webhooks, you can receive real-time updates for events happening on-chain.
You can set up filters to receive updates only on what matters to your use case.
Check the event types supported.
CDP will push notifications to your webhook endpoint via a POST request with a JSON payload containing the on-chain event data.
Before creating the CDP Webhook, let’s first setup the discord bot we’re going to use to post the data received from CDP Webhook.
For this use case, there’s no need to create a custom Discord bot. Let’s just create a Discord Webhook, where
we can post a message to a channel only doing a POST request.
First go to a Discord channel where you’re admin (or you can also create your own server) and click on Edit channel.
Then, click on Integrations on the left menu.
After that, on the Webhooks card, click on Create Webhook.
Now, you can change the bot name and channel that your Discord Webhook Bot will post to by clicking on it.
On the same page click on Copy Webhook URL and keep this URL that we’ll need on the next step.
Test it out, remember to replace DISCORD_WEBHOOK_URL with the one you’ve copied from Discord.
If you wanna skip the step-by-step tutorial, you can clone the node.js SDK repo on github and check
this folder, which contains a
more complete version of the code for this tutorial. We’re using a simplified version on this doc for learning purposes only.You can follow that folder’s README on instructions on how to run it.
You need to set up a https server to receive the api calls made by CDP webhooks.
In this example we’re going to use node.js and express to create a server.Start by creating an empty folder and then set up your node.js project using npm with the following command (remember to setup your Node.js environment):
Report incorrect code
Copy
Ask AI
npm init -y; npm pkg set type="module";
Then, create app.js file inside the same folder:
Report incorrect code
Copy
Ask AI
touch app.js
Let’s now install the project dependencies:
Report incorrect code
Copy
Ask AI
npm install axios express
Once installed you’ll see it in your package.json file:
Paste below code into the app.js file from the example project and replace the PUT_YOUR_DISCORD_URL_HERE with the URL you copied from the last step.
app.js
Report incorrect code
Copy
Ask AI
import express from 'express'import axios from 'axios'const app = express();app.use(express.json());app.post("/", (req, res) => { const data = req.body; const discordWebhookUrl = 'PUT_YOUR_DISCORD_URL_HERE' let messageContent = 'A new ' + data.eventType + ' event was received from the webhook: \n```' messageContent += JSON.stringify(data, null, 2) messageContent += '```\n' messageContent += `Data received at ${new Date().toLocaleString("en-US")}` const postData = { content: messageContent, } axios.post(discordWebhookUrl, postData).then(() => console.log('Successfully called discord.')).catch(console.log); res.sendStatus(200);});const PORT = 3000;app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`);});
Then start the webhook app for listening for webhook events and forwarding it to the discord server.
Report incorrect code
Copy
Ask AI
node app.js
Note that your server will be listening on your localhost port 3000.Now, since your server is listening on localhost, you need to make it accessible from the internet.
You can use tools like Pinggy and Ngrok to set up this tunneling.
What these services do is to create a secure tunnel from your localhost to their server and expose your server running on localhost:3000 through a public address they’ll provide.In this example, let’s use Pinggy to expose port 3000 from your localhost, run the following command in a new terminal:
After running the command, you’ll see an output similar to below:The HTTPS URL you see on the above output is the one you should use when creating your CDP Webhook on the next step.
On the same folder you created your app above, let’s now use coinbase SDK to do a transfer between two wallets and create a webhook listening for that transfer.Let’s install the coinbase SDK as a dependency:
Make sure that these are installed in the same folder as your app.js folder.
Report incorrect code
Copy
Ask AI
npm install @coinbase/coinbase-sdk
Once installed you’ll see it in your package.json file:
After you installed the SDK, lets create a new file on the project:
Report incorrect code
Copy
Ask AI
touch webhook-transfer.js
Then, the first thing you’ll need is to create a CDP API key and download it.You can now copy below code and paste into the empty file we just created:
webhook-transfer.js
Report incorrect code
Copy
Ask AI
import { Coinbase, Webhook, Wallet } from "@coinbase/coinbase-sdk";// Change this to the path of your API key file (if downloaded) from CDP portal.// Make sure your [API key](https://portal.cdp.coinbase.com/projects/api-keys) file path (if downloaded) matches the path on the code you just copied:// `Coinbase.configureFromJson({ filePath: "~/Downloads/cdp_api_key.json" });`// For better security, it is recommended to use environment variables instead of downloading the API key file.Coinbase.configureFromJson({ filePath: "~/Downloads/cdp_api_key.json" });// Change this URL to the one from Pinggyconst webhookNotificationUri = 'YOUR_NOTIFICATION_URL'// Now create a couple of wallets:let myWallet = await Wallet.create();let anotherWallet = await Wallet.create();// After you created the wallet, let's add some USDC funds to it:const faucetTx = await myWallet.faucet(Coinbase.assets.Usdc);// Wait for the faucet transaction to confirm.await faucetTx.wait();// Now use below code to get wallets addresses so we can use it for adding it to the webhook filter.let myWalletAddress = await myWallet.getDefaultAddress();const myWalletAddressId = myWalletAddress.getId();await Webhook.create({ networkId: Coinbase.networks.BaseSepolia, notificationUri: webhookNotificationUri, eventType: 'wallet_activity', eventTypeFilter: { addresses: [myWalletAddressId], },});// Sometimes funds take a few seconds to be available on the wallet, so let's wait 3 secsawait sleep(3000)// For testing this above example, let's now create a transfer between both wallets we created:// Create transfer from myWallet to anotherWalletconst transfer = await myWallet.createTransfer({ amount: 0.0001, assetId: Coinbase.assets.Usdc, destination: anotherWallet, gasless: true, // for USDC, you can add gasless flag, so you don't need to add ETH funds for paying for gas fees});// Wait for the transfer to complete or fail on-chainawait transfer.wait({ intervalSeconds: 1, // check for transfer completion each 1 second timeoutSeconds: 30, // keep checking for 30 seconds});console.log('Transfer was successful: ', transfer.toString());function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
Don’t forget to replace YOUR_NOTIFICATION_URL with the Pinggy (or similar) URL you got on the previous step. Make sure you copy the HTTPS url (webhook notification URL only supports HTTPS).
What the above code does is to create two wallets, a webhook to listen for wallet activity, add some funds to the wallet and then do a transfer between the two wallets, so we can see the webhook working.Now let’s run the above script with the command:
Report incorrect code
Copy
Ask AI
node webhook-transfer.js
This is one example of webhook payload that will be sent to your server for a transfer like we just did above:
Note that it may take a few seconds to a couple minutes for the transaction to be reflected, but after you receive that payload on your express https server, you should be able to see the message posted on Discord like below:
All notifications received on your webhook will now be posted to your discord channel!
By deploying it to Vercel you can get a public URL for receiving webhooks updates, so you don’t need setup
tunneling and don’t need to host it yourself.
Login on your terminal by running the command: vercel login and use the browser to login.
Then, on the project folder, run vercel --prod to deploy it and it will be deployed after a few
seconds. You’ll be asked for a few configs the first time, you can use the default ones.
This command will build your app on vercel and promote to production, which will make your endpoint
publicly available, so it can be called by our CDP Webhooks service.
Now, go to your Vercel dashboard to get the project public URL (1) and
set Discord webhook url as environment variable (2):
To add Discord webhook url as environment variable on Vercel, you should follow the steps:
Enter on the project dashboard (2).
Click settings.
Click Environment Variables on the left menu.
Add the DISCORD_URL variable on the field indicated on the image below:
If variable was successfully added, you should be able to see the entry on the same page:
After you’ve followed the steps and properly set your Discord webhook URL, you’re good to create CDP Webhooks
pointing to you server hosted by Vercel. The guide for creating CDP Webhooks is on previous section.