> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenderly.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Monitor UniswapV3 Pool Creation

> Learn how to use Tenderly Web3 Actions to monitor new pool creations in UniswapV3Factory and perform automated actions.

In this tutorial, we'll show you how to set up a **Tenderly Web3 Action to monitor new pool creations in the UniswapV3Factory contract** and perform automated actions. This project demonstrates how to use Web3 Actions to interact with smart contracts and Tenderly's features to create a custom monitoring system.

<Card title="UniswapV3Factory monitoring Web3 Action template" href="" />

## Project Overview

The purpose of this project is to set up a system that monitors new pool creations in the UniswapV3Factory contract and performs automated actions when specific conditions are met. Here's a quick breakdown of the project's flow:

1. The Web3 Action listens for `PoolCreated` events from the UniswapV3Factory contract on the Ethereum mainnet.
2. When an event is detected, it extracts the new pool's address from the event data.
3. The action adds the new pool contract to your Tenderly project and tags it for easier management.

## Prerequisites

Before you begin, make sure you have the following:

* [Tenderly CLI](https://github.com/Tenderly/tenderly-cli) installed
* [Node.js](https://nodejs.org/) (v20 currently supported)
* [npm](https://www.npmjs.com/)
* A Tenderly account and project

## Setup

Let's go through the steps to set up your `UniswapV3Factory` Monitoring system:

<Steps>
  ### Create a New Tenderly Project

  If you haven't already, create a new project in your Tenderly dashboard or use an existing one.

  ### Create an Alert in Tenderly

  1. Log into your Tenderly Dashboard
  2. Navigate to your project
  3. Go to the **Alerts** tab and click on **New Alert**
  4. Set the Alert Type to **Event Emitted**
  5. Configure the alert:
     * **Contract Address:** `0x1f98431c8ad98523631ae4a59f267346ea31f984` (UniswapV3Factory contract)
     * **Event Signature:** `PoolCreated(address,address,uint24,int24,address)`
     * Name your alert appropriately for easy reference
  6. Save the alert and note down the `id` of an alert for later use

  ### Initialize Web3 Action Project

  Open a terminal and run the following command to initialize a new Web3 Actions project:

  ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  tenderly actions init
  ```

  Select your Tenderly project when prompted and choose a directory name for your actions.

  ### Configure tenderly.yaml

  Update the `tenderly.yaml` file with the following configuration:

  ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  account_id: "<YOUR_ACCOUNT_ID>"
  actions:
    <YOUR_ACCOUNT_ID>/<YOUR_PROJECT_SLUG>:
      runtime: v2
      sources: actions
      specs:
        uniswapV3:
          description: "Monitoring UniswapV3 Factory Contract and adding Child/Pool to Contracts page with proper tag"
          function: uniswapV3Monitoring:actionFn
          trigger:
            type: alert
            alert: { <ALERT_ID> }
          execution_type: parallel
  project_slug: "<YOUR_PROJECT_SLUG>"
  ```

  Replace `<YOUR_ACCOUNT_ID>`, `<YOUR_PROJECT_SLUG>`, and `<ALERT_ID>` with your actual Tenderly `Account Name`, `Project Slug`, and the `Alert ID` you noted earlier.

  ### Set Up Secrets

  Add the following secret to your Tenderly project settings:

  * `ACCESS-KEY`: Your Tenderly [API access key](/platform/account/projects/api-tokens)

  To add secrets, go to your Tenderly project settings and navigate to the "Secrets" section.

  ### Implement the Web3 Action

  Create a new file in your actions directory named `uniswapV3Monitoring.ts` and implement your Web3 Action logic as follows:

  ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  const ethers = require('ethers');

  const actionFn = async (context: Context, alertEvent: AlertEvent) => {
    const key = await context.secrets.get('ACCESS-KEY');

    const accountSlug = '<YOUR_ACCOUNT_ID>';
    const projectSlug = '<YOUR_PROJECT_SLUG>';
    const tagName = 'pool';

    const tenderly = new Tenderly({
      accountName: accountSlug,
      projectName: projectSlug,
      accessKey: key,
      network: Number(alertEvent.network),
    });

    const poolCreatedSignature = ethers.utils.id("PoolCreated(address,address,uint24,int24,address)");

    let poolAddress = "";
    for (const log of alertEvent.logs) {
      if (log.topics[0] === poolCreatedSignature) {
        const data = log.data;
        const addressHex = data.substring(data.length - 40);
        poolAddress = ethers.utils.getAddress('0x' + addressHex).toLowerCase();
        break;
      }
    }

    try {
      await tenderly.contracts.add(poolAddress, {
        displayName: 'Pool'
      });
      await tenderly.contracts.update(poolAddress, { appendTags: [tagName] });
      console.log(`Pool contract is: ${poolAddress}, and has been added with tag ${tagName}`);
    } catch (error) {
      console.error('Error adding contract:', error);
    }
  };

  module.exports = { actionFn };
  ```

  Make sure to replace `<YOUR_ACCOUNT_ID>` and `<YOUR_PROJECT_SLUG>` with your actual Tenderly `Account Name` and `Project Slug`.

  ### Deployment

  To deploy your Web3 Action, use the Tenderly CLI:

  ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  tenderly actions deploy
  ```

  This command will deploy the action defined in your `tenderly.yaml` file.
</Steps>

## How it Works

The Web3 Action you've set up will automatically trigger whenever the `PoolCreated` event is emitted by the `UniswapV3Factory` contract. Here's a breakdown of the `actionFn` function:

1. Retreive the `ACCESS-KEY` secret from the Tenderly context.
2. Initialize a new Tenderly SDK instance with your account and project details.
3. Define the `PoolCreated` event signature using ethers.js.
4. Loop through the event logs to find the `PoolCreated` event and extracts the new pool's address.
5. Using the Tenderly SDK, add the new pool contract to your Tenderly project with the display name `Pool`.
6. Tag the new pool contract with the `pool` tag for easier management.
7. Log the pool address and confirmation of the tagging process.

<Note>
  This implementation automatically adds new Uniswap V3 pools to your Tenderly project and tags them, making it easier to monitor and manage these contracts.
</Note>

## Customization

To modify the behavior of your Web3 Action:

1. Edit the `actionFn` in the `uniswapV3Monitoring.ts` file.
2. You can change the `tagName` variable to use a different tag for the pools.
3. Add additional logic to process more information from the event or perform other actions with the Tenderly SDK.

For example, to add more detailed logging:

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
console.log(`New pool created: ${poolAddress}`);
console.log(`Network: ${alertEvent.network}`);
console.log(`Transaction hash: ${alertEvent.hash}`);
```

## Monitoring and Troubleshooting

To ensure your Web3 Action is working correctly:

* Monitor your Web3 Action executions in the Tenderly dashboard
* Check the Tenderly logs for any error messages or execution details
* Use Tenderly's debugging tools to inspect transaction details and contract interactions
* Check your Tenderly project's Contracts page to see the newly added and tagged pool contracts

<Warning>
  This setup is specifically designed to monitor the `UniswapV3Factory` contract on the Ethereum mainnet.
</Warning>

## Conclusion

You've now set up a custom monitoring system using Tenderly Web3 Actions to track new pool creations in the `UniswapV3Factory` contract. This project demonstrates how to interact with smart contracts, use Tenderly's SDK, and create an automated system for monitoring and responding to specific blockchain events.

For more information on Uniswap V3 and its contracts, refer to the [Uniswap V3 documentation](https://developers.uniswap.org/protocol/reference/core/UniswapV3Factory).
