> ## 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.

# 监控 UniswapV3 池的创建

> 学习如何使用 Tenderly Web3 Actions 监控 UniswapV3Factory 中的新池创建并执行自动化操作。

在本教程中，我们将向您展示如何设置 **Tenderly Web3 Action 以监控 UniswapV3Factory 合约中的新池创建** 并执行自动化操作。本项目演示了如何使用 Web3 Actions 与智能合约交互，并利用 Tenderly 的功能创建自定义监控系统。

<Card title="UniswapV3Factory 监控 Web3 Action 模板" href="" />

## 项目概览

本项目的目的是设置一个系统来监控 UniswapV3Factory 合约中的新池创建，并在满足特定条件时执行自动化操作。以下是项目流程的简要说明：

1. Web3 Action 监听以太坊主网上 UniswapV3Factory 合约的 `PoolCreated` 事件。
2. 检测到事件时，从事件数据中提取新池的地址。
3. Action 将新池合约添加到您的 Tenderly 项目中，并为其添加标签以便于管理。

## 前提条件

在开始之前，请确保您已具备：

* 已安装 [Tenderly CLI](https://github.com/Tenderly/tenderly-cli)
* [Node.js](https://nodejs.org/)（当前支持 v20）
* [npm](https://www.npmjs.com/)
* Tenderly 账户和项目

## 设置

让我们一步步设置您的 `UniswapV3Factory` 监控系统：

<Steps>
  ### 创建新的 Tenderly 项目

  如果您还没有项目，请在您的 Tenderly dashboard 中创建一个新项目，或使用现有项目。

  ### 在 Tenderly 中创建 Alert

  1. 登录您的 Tenderly Dashboard
  2. 导航到您的项目
  3. 前往 **Alerts** 选项卡并点击 **New Alert**
  4. 将 Alert Type 设置为 **Event Emitted**
  5. 配置告警：
     * **合约地址：** `0x1f98431c8ad98523631ae4a59f267346ea31f984`（UniswapV3Factory 合约）
     * **事件签名：** `PoolCreated(address,address,uint24,int24,address)`
     * 为您的告警命名以便于引用
  6. 保存告警并记下告警的 `id` 以备后用

  ### 初始化 Web3 Action 项目

  打开终端并运行以下命令来初始化一个新的 Web3 Actions 项目：

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

  出现提示时选择您的 Tenderly 项目，并为您的 actions 选择一个目录名称。

  ### 配置 tenderly.yaml

  使用以下配置更新 `tenderly.yaml` 文件：

  ```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>"
  ```

  将 `<YOUR_ACCOUNT_ID>`、`<YOUR_PROJECT_SLUG>` 和 `<ALERT_ID>` 替换为您实际的 Tenderly `Account Name`、`Project Slug` 和您之前记下的 `Alert ID`。

  ### 设置 Secrets

  将以下 secret 添加到您的 Tenderly 项目设置中：

  * `ACCESS-KEY`：您的 Tenderly [API access key](/platform/account/projects/api-tokens)

  要添加 secrets，前往您的 Tenderly 项目设置并导航到 "Secrets" 部分。

  ### 实现 Web3 Action

  在您的 actions 目录中创建一个名为 `uniswapV3Monitoring.ts` 的新文件，并按如下方式实现您的 Web3 Action 逻辑：

  ```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 };
  ```

  请确保将 `<YOUR_ACCOUNT_ID>` 和 `<YOUR_PROJECT_SLUG>` 替换为您实际的 Tenderly `Account Name` 和 `Project Slug`。

  ### 部署

  要部署您的 Web3 Action，请使用 Tenderly CLI：

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

  此命令将部署您 `tenderly.yaml` 文件中定义的 action。
</Steps>

## 工作原理

您设置的 Web3 Action 将在 `UniswapV3Factory` 合约发出 `PoolCreated` 事件时自动触发。以下是 `actionFn` 函数的分解：

1. 从 Tenderly context 中检索 `ACCESS-KEY` secret。
2. 使用您的账户和项目详情初始化新的 Tenderly SDK 实例。
3. 使用 ethers.js 定义 `PoolCreated` 事件签名。
4. 循环遍历事件日志以查找 `PoolCreated` 事件并提取新池的地址。
5. 使用 Tenderly SDK 将新池合约以显示名称 `Pool` 添加到您的 Tenderly 项目。
6. 用 `pool` 标签为新池合约打标签以便于管理。
7. 记录池地址和打标签过程的确认信息。

<Note>
  此实现自动将新的 Uniswap V3 池添加到您的 Tenderly 项目并为其打标签，使监控和管理这些合约变得更容易。
</Note>

## 自定义

要修改您 Web3 Action 的行为：

1. 编辑 `uniswapV3Monitoring.ts` 文件中的 `actionFn`。
2. 您可以更改 `tagName` 变量以对池使用不同的标签。
3. 添加额外的逻辑以处理事件中的更多信息或使用 Tenderly SDK 执行其他操作。

例如，要添加更详细的日志记录：

```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}`);
```

## 监控和故障排除

为确保您的 Web3 Action 正常工作：

* 在 Tenderly dashboard 中监控您的 Web3 Action 执行
* 检查 Tenderly 日志以查看任何错误消息或执行详情
* 使用 Tenderly 的调试工具检查事务详情和合约交互
* 查看您 Tenderly 项目的 Contracts 页面以查看新添加并已打标签的池合约

<Warning>
  此设置专门用于监控以太坊主网上的 `UniswapV3Factory` 合约。
</Warning>

## 总结

您现在已使用 Tenderly Web3 Actions 设置了一个自定义监控系统，用于跟踪 `UniswapV3Factory` 合约中的新池创建。本项目演示了如何与智能合约交互、使用 Tenderly 的 SDK，以及创建一个用于监控和响应特定区块链事件的自动化系统。

有关 Uniswap V3 及其合约的更多信息，请参阅 [Uniswap V3 文档](https://developers.uniswap.org/protocol/reference/core/UniswapV3Factory)。
