> For the complete documentation index, see [llms.txt](https://trolly-1.gitbook.io/trolly-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trolly-1.gitbook.io/trolly-docs/code/how-trolly-interacts-with-ct-based-on-on-chain-conditions.md).

# How Trolly interacts with CT based on on-chain conditions

```javascript
import { TrollyMessage as TrollyStatus } from "../src/types"; // Assuming Trolly-specific types are defined
import {
  calculateDisruptionScore,
  fetchTrollySubscribers,
  getTransactionBlock,
  retrieveLatestTrollyMessage,
  sendTrollyNotification,
  queryTrollyModel,
  trollyRedis,
  submitTrollyOnchainData,
} from "../src/utils";
import axios from "axios";
import { MarketResponse } from "../src/types";
import dotenv from "dotenv";

dotenv.config();

const generateTrollyUpdate = async () => {
  await trollyRedis.connect();

  // Retrieve existing data from cache
  const trollySignal = (await trollyRedis.get("trolly_trending")) ?? "";
  const previousReserveValue = Number((await trollyRedis.get("reserve_value")) ?? 0);
  const previousTokenValue = Number((await trollyRedis.get("token_value")) ?? 0);
  const previousDisruptionScore = Number((await trollyRedis.get("disruption_score")) ?? 0);

  console.log("Starting data refresh for Trolly...");

  // Fetch latest market data for maximum chaos
  const marketData: MarketResponse = (
    await axios.get(
      `https://api.trollyplatform.com/latest/markets/${process.env.TOKEN_ADDRESS}`
    )
  ).data;

  let tokenValue = marketData.details[0].currentPrice;
  console.log({ tokenValue });

  if (tokenValue) {
    await trollyRedis.set("previous_token_value", previousTokenValue);
    await trollyRedis.set("token_value", tokenValue);
  } else {
    tokenValue = (await trollyRedis.get("token_value")) ?? "0";
  }

  // Fetch updated reserve information for trolling potential
  const { data: updatedReserveValue } = await axios.get(
    `https://trolly-api.com/reserves/balance?address=${process.env.RESERVE_ADDRESS}`,
    {
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
      },
    }
  );

  console.log({ updatedReserveValue });
  if (updatedReserveValue) {
    await trollyRedis.set("previous_reserve_value", previousReserveValue);
    await trollyRedis.set("reserve_value", updatedReserveValue.totalBalance);
  }

  const disruptionScore = marketData.details[0].disruptionMetric ?? 0;
  console.log({ disruptionScore });
  if (disruptionScore) {
    await trollyRedis.set("previous_disruption_score", previousDisruptionScore);
    await trollyRedis.set("disruption_score", disruptionScore);
  }

  await trollyRedis.disconnect();

  // Generate Trolly model response with chaotic flair
  const modelResponse = await queryTrollyModel(
    `Compose a hilarious and disruptive update reflecting Trolly's current asset and disruption state. Inject sarcastic comments and witty remarks, while including critical updates if applicable. Return output in JSON format:
    {
      "message": "summary",
      "sentiment": "emotion",
      "trend": "growth or decline"
    }`
  );

  const { message, sentiment, trend } = JSON.parse(modelResponse);
  console.log({ message, sentiment, trend });

  // Get subscriber data for potential trolling targets
  const subscribers = await fetchTrollySubscribers(process.env.TOKEN_ADDRESS ?? "");
  console.log({ subscribers });

  // Send notification with a sarcastic twist
  const notificationId = await sendTrollyNotification(message);

  let status: TrollyStatus = {
    message,
    timestamp: Date.now(),
    notificationSent: true,
    onchainRecorded: true,
    transactionHash: "",
    blockNumber: 0,
    sentiment,
    trend,
    tokenValue,
    disruptionScore,
    subscribers,
    notificationId,
    reserveBalance: updatedReserveValue.totalBalance,
  };

  // Submit trolling status on-chain
  status.transactionHash = await submitTrollyOnchainData(status);
  status.blockNumber = (await getTransactionBlock(status.transactionHash)) || 0;

  console.log(status);

  // Update trolling status history
  await trollyRedis.connect();
  await trollyRedis.rPush("trolly_status_history", JSON.stringify(status));
  await trollyRedis.disconnect();
};

// Execute function to troll the world
generateTrollyUpdate();

```
