浏览代码

add sui metrics

Daniel Chew 8 月之前
父节点
当前提交
117f6043ba

+ 30 - 1
apps/price_pusher/src/balance-tracker.ts

@@ -5,6 +5,8 @@ import { IBalanceTracker } from "./interface";
 import { EvmBalanceTracker } from "./evm/balance-tracker";
 import { SuperWalletClient } from "./evm/super-wallet";
 import { AptosBalanceTracker } from "./aptos/balance-tracker";
+import { SuiBalanceTracker } from "./sui/balance-tracker";
+import { SuiClient } from "@mysten/sui/client";
 
 /**
  * Parameters for creating an EVM balance tracker
@@ -64,6 +66,33 @@ export function createAptosBalanceTracker(
   });
 }
 
+/**
+ * Parameters for creating a Sui balance tracker
+ */
+export interface CreateSuiBalanceTrackerParams {
+  client: SuiClient;
+  address: string;
+  network: string;
+  updateInterval: DurationInSeconds;
+  metrics: PricePusherMetrics;
+  logger: Logger;
+}
+
+/**
+ * Factory function to create a balance tracker for Sui chain
+ */
+export function createSuiBalanceTracker(
+  params: CreateSuiBalanceTrackerParams,
+): IBalanceTracker {
+  return new SuiBalanceTracker({
+    client: params.client,
+    address: params.address,
+    network: params.network,
+    updateInterval: params.updateInterval,
+    metrics: params.metrics,
+    logger: params.logger,
+  });
+}
+
 // Additional factory functions for other chains would follow the same pattern:
-// export function createSuiBalanceTracker(params: CreateSuiBalanceTrackerParams): IBalanceTracker { ... }
 // export function createSolanaBalanceTracker(params: CreateSolanaBalanceTrackerParams): IBalanceTracker { ... }

+ 61 - 0
apps/price_pusher/src/sui/balance-tracker.ts

@@ -0,0 +1,61 @@
+import { SuiClient } from "@mysten/sui/client";
+import { BaseBalanceTracker, BaseBalanceTrackerConfig } from "../interface";
+
+/**
+ * Sui-specific configuration for balance tracker
+ */
+export interface SuiBalanceTrackerConfig extends BaseBalanceTrackerConfig {
+  /** Sui client instance */
+  client: SuiClient;
+}
+
+/**
+ * Sui-specific implementation of the balance tracker
+ */
+export class SuiBalanceTracker extends BaseBalanceTracker {
+  private client: SuiClient;
+
+  constructor(config: SuiBalanceTrackerConfig) {
+    super({
+      ...config,
+      logger: config.logger.child({ module: "SuiBalanceTracker" }),
+    });
+
+    this.client = config.client;
+  }
+
+  /**
+   * Sui-specific implementation of balance update
+   */
+  protected async updateBalance(): Promise<void> {
+    try {
+      // Get all coins owned by the address
+      const { data: coins } = await this.client.getCoins({
+        owner: this.address,
+      });
+
+      // Sum up all coin balances
+      const totalBalance = coins.reduce((acc, coin) => {
+        return acc + BigInt(coin.balance);
+      }, BigInt(0));
+
+      // Convert to a normalized number for reporting (SUI has 9 decimals)
+      const normalizedBalance = Number(totalBalance) / 1e9;
+
+      this.metrics.updateWalletBalance(
+        this.address,
+        this.network,
+        normalizedBalance,
+      );
+
+      this.logger.debug(
+        `Updated Sui wallet balance: ${this.address} = ${normalizedBalance} SUI`,
+      );
+    } catch (error) {
+      this.logger.error(
+        { error },
+        "Error fetching Sui wallet balance for metrics",
+      );
+    }
+  }
+}

+ 41 - 6
apps/price_pusher/src/sui/command.ts

@@ -9,6 +9,9 @@ import { SuiPriceListener, SuiPricePusher } from "./sui";
 import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
 import pino from "pino";
 import { filterInvalidPriceItems } from "../utils";
+import { PricePusherMetrics } from "../metrics";
+import { createSuiBalanceTracker } from "../balance-tracker";
+import { SuiClient } from "@mysten/sui/client";
 
 export default {
   command: "sui",
@@ -72,6 +75,8 @@ export default {
     ...options.pushingFrequency,
     ...options.logLevel,
     ...options.controllerLogLevel,
+    ...options.enableMetrics,
+    ...options.metricsPort,
   },
   handler: async function (argv: any) {
     const {
@@ -89,6 +94,8 @@ export default {
       accountIndex,
       logLevel,
       controllerLogLevel,
+      enableMetrics,
+      metricsPort,
     } = argv;
 
     const logger = pino({ level: logLevel });
@@ -101,11 +108,8 @@ export default {
       mnemonic,
       `m/44'/784'/${accountIndex}'/0'/0'`,
     );
-    logger.info(
-      `Pushing updates from wallet address: ${keypair
-        .getPublicKey()
-        .toSuiAddress()}`,
-    );
+    const suiAddress = keypair.getPublicKey().toSuiAddress();
+    logger.info(`Pushing updates from wallet address: ${suiAddress}`);
 
     let priceItems = priceConfigs.map(({ id, alias }) => ({ id, alias }));
 
@@ -123,12 +127,22 @@ export default {
 
     priceItems = existingPriceItems;
 
+    // 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 pythListener = new PythPriceListener(
       hermesClient,
       priceItems,
       logger.child({ module: "PythPriceListener" }),
     );
 
+    const suiClient = new SuiClient({ url: endpoint });
+
     const suiListener = new SuiPriceListener(
       pythStateId,
       wormholeStateId,
@@ -137,6 +151,7 @@ export default {
       logger.child({ module: "SuiPriceListener" }),
       { pollingFrequency },
     );
+
     const suiPusher = await SuiPricePusher.createWithAutomaticGasPool(
       hermesClient,
       logger.child({ module: "SuiPricePusher" }),
@@ -155,9 +170,29 @@ export default {
       suiListener,
       suiPusher,
       logger.child({ module: "Controller" }, { level: controllerLogLevel }),
-      { pushingFrequency },
+      {
+        pushingFrequency,
+        metrics,
+      },
     );
 
+    // Create and start the balance tracker if metrics are enabled
+    if (metrics) {
+      // For Sui, we'll use a simple network identification approach
+      // In the future, this could be improved by querying the network directly
+      const balanceTracker = createSuiBalanceTracker({
+        client: suiClient,
+        address: suiAddress,
+        network: "sui", // Simply use "sui" as the network name for now
+        updateInterval: pushingFrequency,
+        metrics,
+        logger,
+      });
+
+      // Start the balance tracker
+      await balanceTracker.start();
+    }
+
     controller.start();
   },
 };