소스 검색

add aptos metrics

Daniel Chew 8 달 전
부모
커밋
398faa2228
3개의 변경된 파일139개의 추가작업 그리고 1개의 파일을 삭제
  1. 74 0
      apps/price_pusher/src/aptos/balance-tracker.ts
  2. 34 1
      apps/price_pusher/src/aptos/command.ts
  3. 31 0
      apps/price_pusher/src/balance-tracker.ts

+ 74 - 0
apps/price_pusher/src/aptos/balance-tracker.ts

@@ -0,0 +1,74 @@
+import { AptosClient } from "aptos";
+import { BaseBalanceTracker, BaseBalanceTrackerConfig } from "../interface";
+
+/**
+ * Aptos-specific configuration for balance tracker
+ */
+export interface AptosBalanceTrackerConfig extends BaseBalanceTrackerConfig {
+  /** Aptos node endpoint URL */
+  endpoint: string;
+  /** Aptos account address */
+  address: string;
+  /** Optional decimal places for APT token (default: 8) */
+  decimals?: number;
+}
+
+/**
+ * Aptos-specific implementation of the balance tracker
+ */
+export class AptosBalanceTracker extends BaseBalanceTracker {
+  private client: AptosClient;
+  private aptosAddress: string;
+  private decimals: number;
+
+  constructor(config: AptosBalanceTrackerConfig) {
+    super({
+      ...config,
+      logger: config.logger.child({ module: "AptosBalanceTracker" }),
+    });
+
+    this.client = new AptosClient(config.endpoint);
+    this.aptosAddress = config.address;
+    // APT has 8 decimal places by default
+    this.decimals = config.decimals ?? 8;
+  }
+
+  /**
+   * Aptos-specific implementation of balance update
+   * Fetches the native APT balance for the configured address
+   */
+  protected async updateBalance(): Promise<void> {
+    try {
+      // Get account resource to check the balance
+      const accountResource = await this.client.getAccountResource(
+        this.aptosAddress,
+        "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
+      );
+
+      // Extract the balance value from the account resource
+      const rawBalance = (accountResource.data as any).coin.value;
+
+      // Convert the balance to a bigint
+      const balance = BigInt(rawBalance);
+
+      // Calculate the normalized balance for display
+      const normalizedBalance = Number(balance) / Math.pow(10, this.decimals);
+
+      // Update metrics with the new balance
+      this.metrics.updateWalletBalance(
+        this.address,
+        this.network,
+        normalizedBalance,
+      );
+
+      this.logger.debug(
+        `Updated Aptos wallet balance: ${this.address} = ${normalizedBalance.toString()} APT (raw: ${balance.toString()})`,
+      );
+    } catch (error) {
+      this.logger.error(
+        { error },
+        "Error fetching Aptos wallet balance for metrics",
+      );
+    }
+  }
+}

+ 34 - 1
apps/price_pusher/src/aptos/command.ts

@@ -13,6 +13,9 @@ import {
 import { AptosAccount } from "aptos";
 import pino from "pino";
 import { filterInvalidPriceItems } from "../utils";
+import { PricePusherMetrics } from "../metrics";
+import { createAptosBalanceTracker } from "../balance-tracker";
+
 export default {
   command: "aptos",
   describe: "run price pusher for aptos",
@@ -40,6 +43,8 @@ export default {
     ...options.pushingFrequency,
     ...options.logLevel,
     ...options.controllerLogLevel,
+    ...options.enableMetrics,
+    ...options.metricsPort,
   },
   handler: async function (argv: any) {
     // FIXME: type checks for this
@@ -54,6 +59,8 @@ export default {
       overrideGasPriceMultiplier,
       logLevel,
       controllerLogLevel,
+      enableMetrics,
+      metricsPort,
     } = argv;
 
     const logger = pino({ level: logLevel });
@@ -61,6 +68,14 @@ export default {
     const priceConfigs = readPriceConfigFile(priceConfigFile);
     const hermesClient = new HermesClient(priceServiceEndpoint);
 
+    // Initialize metrics if enabled
+    let metrics: PricePusherMetrics | undefined;
+    if (enableMetrics) {
+      metrics = new PricePusherMetrics(logger.child({ module: "Metrics" }));
+      metrics.start(metricsPort);
+      logger.info(`Metrics server started on port ${metricsPort}`);
+    }
+
     const mnemonic = fs.readFileSync(mnemonicFile, "utf-8").trim();
     const account = AptosAccount.fromDerivePath(
       APTOS_ACCOUNT_HD_PATH,
@@ -113,9 +128,27 @@ export default {
       aptosListener,
       aptosPusher,
       logger.child({ module: "Controller" }, { level: controllerLogLevel }),
-      { pushingFrequency },
+      {
+        pushingFrequency,
+        metrics,
+      },
     );
 
+    // Create and start the balance tracker if metrics are enabled
+    if (metrics) {
+      const balanceTracker = createAptosBalanceTracker({
+        address: account.address().toString(),
+        endpoint,
+        network: "aptos", // You might want to extract network name from config
+        updateInterval: pushingFrequency,
+        metrics,
+        logger: logger.child({ module: "AptosBalanceTracker" }),
+      });
+
+      // Start the balance tracker
+      await balanceTracker.start();
+    }
+
     controller.start();
   },
 };

+ 31 - 0
apps/price_pusher/src/balance-tracker.ts

@@ -4,6 +4,7 @@ import { DurationInSeconds } from "./utils";
 import { IBalanceTracker } from "./interface";
 import { EvmBalanceTracker } from "./evm/balance-tracker";
 import { SuperWalletClient } from "./evm/super-wallet";
+import { AptosBalanceTracker } from "./aptos/balance-tracker";
 
 /**
  * Parameters for creating an EVM balance tracker
@@ -33,6 +34,36 @@ export function createEvmBalanceTracker(
   });
 }
 
+/**
+ * Parameters for creating an Aptos balance tracker
+ */
+export interface CreateAptosBalanceTrackerParams {
+  endpoint: string;
+  address: string;
+  network: string;
+  updateInterval: DurationInSeconds;
+  metrics: PricePusherMetrics;
+  logger: Logger;
+  decimals?: number;
+}
+
+/**
+ * Factory function to create a balance tracker for Aptos chain
+ */
+export function createAptosBalanceTracker(
+  params: CreateAptosBalanceTrackerParams,
+): IBalanceTracker {
+  return new AptosBalanceTracker({
+    endpoint: params.endpoint,
+    address: params.address,
+    network: params.network,
+    updateInterval: params.updateInterval,
+    metrics: params.metrics,
+    logger: params.logger,
+    decimals: params.decimals,
+  });
+}
+
 // Additional factory functions for other chains would follow the same pattern:
 // export function createSuiBalanceTracker(params: CreateSuiBalanceTrackerParams): IBalanceTracker { ... }
 // export function createSolanaBalanceTracker(params: CreateSolanaBalanceTrackerParams): IBalanceTracker { ... }