> ## Documentation Index
> Fetch the complete documentation index at: https://creator-a1160a86.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Alert New Pool Creation

> Monitor on-chain activity for new DLMM pool creation for a specific token and alert your users  via Dialect notifications

Dialect alerts is a powerful infra that helps developers setup up in-app, push, email, telegram notifications
for users with simple setup by abstracting the complexity of the messaging services.

This recipe demostrates how to setup a monitoring system to alert users via Dialect notifications when new pools are created
with a specific token on DLMM.

## Prerequisites

* Before you proceed, ensure you have your app registered in [dialect dashboard](https://docs.dialect.to/alerts/setup/register-app)
* setup a [interface](https://docs.dialect.to/alerts/integrate-inbox) to view alerts triggered.

## Project Setup

Create a new project directory and initialize it:

```bash theme={null}
mkdir pool-monitor
cd pool-monitor
npm init -y
```

## Install Dependencies

Install the required packages:

```bash npm theme={null}
npm install @dialectlabs/sdk @dialectlabs/blockchain-sdk-solana @dialectlabs/monitor @saros-finance/dlmm-sdk @solana/web3.js bs58 rxjs
```

```bash yarn theme={null}
yarn add @dialectlabs/sdk @dialectlabs/blockchain-sdk-solana @dialectlabs/monitor @saros-finance/dlmm-sdk @solana/web3.js bs58 rxjs
```

## TypeScript Configuration

Create a `tsconfig.json` file:

```json tsconfig.json expandable theme={null}
{
  "compilerOptions": {
    "target": "esnext",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "allowJs": true,
    "skipLibCheck": true,
    "declaration": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
```

## Update package.json

Add the module type to your `package.json`:

```json package.json icon="code" lines theme={null}
  "name": "pool-monitor",
  "version": "1.0.0",
  "type": "module", // [!code ++]
  "scripts": {
    "start": "node dist/index.js",
    "build": "tsc",
    "dev": "tsc && node dist/index.js"
  },
```

## Create Service Files

### Wallet Adapter

We will be needing a wallet adapter that will be used by dialect sdk to sign messages. it is prefered to use
`NodeDialectSolanaWalletAdapter`  from @dialectlabs/blockchain-sdk-solana . But now I will show you how to create a
custom wallet adapter that will be used by dialect sdk to sign messages.

```javascript src/wallet.js theme={null}
import { WalletAdapter } from '@solana/wallet-adapter-base';

export class CustomWalletAdapter extends WalletAdapter {
  constructor(keypair) {
    super();
    this.keypair = keypair;
  }

  get publicKey() {
    return this.keypair.publicKey;
  }

  async signTransaction(transaction) {
    transaction.sign(this.keypair);
    return transaction;
  }

  async signAllTransactions(transactions) {
    return transactions.map(tx => {
      tx.sign(this.keypair);
      return tx;
    });
  }
}
```

### Saros DLMM Service

Create `src/service.js` and create an instance of `LiquidityBookServices` from @saros-finance/dlmm-sdk.
This client object will be sufficient for our monitoring system.

```javascript src/service.js theme={null}
import { LiquidityBookServices, MODE } from "@saros-finance/dlmm-sdk";

// Initialize Saros DLMM SDK
export const sarosDLMM = new LiquidityBookServices({
  mode: MODE.DEVNET,
  options: {
    rpcUrl: process.env.RPC_ENDPOINT || "https://api.devnet.solana.com",
  },
});
```

## Main Monitoring Script

Let's split the monitoring system into three main components:

1. **Client SDK Initialization** - Setting up Dialect and Saros SDKs
2. **On-Chain Tracking** - Listen to pool creation events
3. **Monitor Setup** - Monitor setup that will process and emit alerts to dialect infra, that will be used to send notifications to users.

### 1. Client SDK Initialization

First, let's set up the Dialect SDK client in a separate file called `pool-tracker.ts`.

> [!NOTE]
>
> The wallet used here is the registered wallet in dialect dashboard.

```javascript src/pool-tracker.ts theme={null}
import { Dialect } from "@dialectlabs/sdk";
import { SolanaSdkFactory } from "@dialectlabs/blockchain-sdk-solana";
import { Keypair } from "@solana/web3.js";
import bs58 from "bs58";
import { CustomWalletAdapter } from "./wallet.js";

// Initialize Dialect SDK for notifications
export const initializeDialectSDK = (walletSecretKey: string) => {
  const dialectSolanaSDK = Dialect.sdk(
    { environment: "production" },
    SolanaSdkFactory.create({ 
      wallet: new CustomWalletAdapter(Keypair.fromSecretKey(
        bs58.decode(walletSecretKey)
      ))
    })
  );
  
  return dialectSolanaSDK;
};
```

### 2. On-Chain Tracking

Now we will track the new DLMM pool creations for PYUSD token on devnet. We will setup a source that will
receive the data that we are interested in and emit it to the monitor setup. Then by using `listenNewPoolAddress` and
`fetchPoolMetadata` methods we will be able to track the new pool created for PYUSD token.

```javascript src/pool-tracker.ts diff icon="code" lines theme={null}
import { Dialect } from "@dialectlabs/sdk";
import { SolanaSdkFactory } from "@dialectlabs/blockchain-sdk-solana";
import { Keypair } from "@solana/web3.js";
import bs58 from "bs58";
import { CustomWalletAdapter } from "./wallet.js";
import { sarosDLMM } from "./service.js"; // [!code ++]
import { Subject } from "rxjs"; // [!code ++]
import { SourceData } from "@dialectlabs/monitor"; // [!code ++]

export const initializeDialectSDK = (walletSecretKey: string) => {
  const dialectSolanaSDK = Dialect.sdk(
    { environment: "production" },
    SolanaSdkFactory.create({ 
      wallet: new CustomWalletAdapter(Keypair.fromSecretKey(
        bs58.decode(walletSecretKey)
      ))
    })
  );
  
  return dialectSolanaSDK;
};

// PYUSD mint address on devnet
const TARGET_BASE_MINT = "CXk2AMBfi3TwaEL2468s6zP8xq9NxTXjp9gjMgzeUynM"; // [!code ++]

type MessageType = {  // [!code ++:4]
  POOL_ADDRESS: string;
  BASE_MINT: string;
};

const subject = new Subject<SourceData<MessageType>>(); // [!code ++]

const alertPoolCreation = async () => { // [!code ++:18]
  await sarosDLMM.listenNewPoolAddress(async (poolAddress: string) => {
    const poolMetadata = await sarosDLMM.fetchPoolMetadata(poolAddress);

    if (poolMetadata.baseMint === TARGET_BASE_MINT) {
      subject.next({
        data: {
          POOL_ADDRESS: poolAddress,
          BASE_MINT: poolMetadata.baseMint,
        },
        groupingKey: poolAddress,
      });
    }
  });
};

alertPoolCreation();
```

### 3. Monitor Setup

Now setup the monitor that will listen to the subject, process the data given by the subject and
emit the alert to the dialect desired message.

> [!NOTE]
>
> The `transform` step is used to add constraints on the data and filter out unwanted messages. But
> in our case we are not adding any constraints on the data.

> [!NOTE]
>
> The `notify` step is used to emit the alert to the dialect desired message and  `dialectSdk` is used
> process the raw data into the desired message.

```javascript src/pool-tracker.ts diff icon="code" lines theme={null}
import { Monitor, Monitors, Pipelines } from "@dialectlabs/monitor"; // [!code ++:2]
import { poolCreationSubject } from "./pool-tracker.js";

const monitor: Monitor<MessageType> = Monitors.builder({ sdk: dialectSolanaSDK }) // [!code ++:25]
  .defineDataSource<MessageType>()
  .push(subject)
  .transform<string, string>({
    keys: ["POOL_ADDRESS"],
    pipelines: [
      Pipelines.createNew<string, MessageType, string>((upstream) =>
        upstream
      ),
    ],
  })
  .notify()
  .dialectSdk(
    ({ value }) => {
      return {
        title: "PYUSD pool creation",
        message: `New PYUSD pool with address ${value} was created`,
      };
    },
    { dispatch: "broadcast" }
  )
  .and()
  .build();

monitor.start();

```

## Running the Monitor

update your `package.json` file to execute `pool-tracker.ts` script:

```json diff package.json  icon="code" lines theme={null}
"start": "node dist/pool-tracker.js", // [!code ++]
```

Build and run the project:

```bash theme={null}
npm run build
npm start
```

On Pool creation, you should see the following output:

```
1 subscriber(s) added: [9vnubELzZnaeRZaHNfmPKHEHdikg9PEsFWPQVXsXdXvb]
1 subscriber(s) added: [{"resourceId":"9vnubELzZnaeRZaHNfmPKHEHdikg9PEsFWPQVXsXdXvb","wallet":"9vnubELzZnaeRZaHNfmPKHEHdikg9PEsFWPQVXsXdXvb"}]
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.