Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- CreateTable
CREATE TABLE "PlatformDailyStats" (
"id" TEXT NOT NULL,
"date" TIMESTAMP(3) NOT NULL,
"totalVolume" BIGINT NOT NULL DEFAULT 0,
"totalFees" BIGINT NOT NULL DEFAULT 0,
"transactionCount" BIGINT NOT NULL DEFAULT 0,
"newInvoices" INTEGER NOT NULL DEFAULT 0,
"newMerchants" INTEGER NOT NULL DEFAULT 0,
"newSubscriptions" INTEGER NOT NULL DEFAULT 0,
"newTickets" INTEGER NOT NULL DEFAULT 0,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "PlatformDailyStats_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "PlatformDailyStats_date_key" ON "PlatformDailyStats"("date");
16 changes: 16 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,19 @@ model DepositAccount {
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: Restrict)
}


// Protocol-wide daily rollup. One row per UTC calendar day, upserted by the
// indexer as events arrive (no scheduled batch job), mirroring how
// MerchantAnalytics/TokenAnalytics are maintained.
model PlatformDailyStats {
id String @id @default(uuid())
date DateTime @unique
totalVolume BigInt @default(0)
totalFees BigInt @default(0)
transactionCount BigInt @default(0)
newInvoices Int @default(0)
newMerchants Int @default(0)
newSubscriptions Int @default(0)
newTickets Int @default(0)
updatedAt DateTime @updatedAt
}
50 changes: 50 additions & 0 deletions src/controllers/admin-analytics.controllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Request, Response } from 'express';
import {
getAnalyticsSummary,
getAnalyticsTimeseries,
getTopTokensByVolume,
} from '../services/analytics.services.js';
import { AppError } from '../utils/errors.js';

const handleError = (error: unknown, req: Request, res: Response, action: string): void => {
if (error instanceof AppError) {
res.status(error.statusCode).json({ error: error.message });
return;
}

console.error(`Failed to ${action}`, {
path: req.path,
method: req.method,
error: error instanceof Error ? error.message : 'Unknown error',
});
res.status(500).json({ error: 'Internal Server Error' });
};

export const getAnalyticsSummaryController = async (req: Request, res: Response): Promise<void> => {
try {
res.status(200).json(await getAnalyticsSummary());
} catch (error) {
handleError(error, req, res, 'load the analytics summary');
}
};

export const getAnalyticsTimeseriesController = async (
req: Request,
res: Response,
): Promise<void> => {
try {
const result = await getAnalyticsTimeseries(req.query as Record<string, unknown>);
res.status(200).json(result);
} catch (error) {
handleError(error, req, res, 'load the analytics timeseries');
}
};

export const getAnalyticsTokensController = async (req: Request, res: Response): Promise<void> => {
try {
const result = await getTopTokensByVolume(req.query as Record<string, unknown>);
res.status(200).json(result);
} catch (error) {
handleError(error, req, res, 'load the token analytics');
}
};
47 changes: 47 additions & 0 deletions src/indexer/handlers/growth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import prisma from '../../config/prisma.js';
import { recordDailyStats } from '../../services/analytics.services.js';
import {
decodeInvoiceCreatedEventData,
decodeMerchantRegisteredEventData,
decodeSubscribedEventData,
type DecodedEvent,
} from '../types.js';

/**
* Falls back to the indexing time only if the RPC response carried no ledger
* close time — every real `getEvents` response does.
*/
const ledgerCloseTime = (event: DecodedEvent): Date => {
if (!event.ledgerClosedAt) return new Date();
const closedAt = new Date(event.ledgerClosedAt);
return Number.isNaN(closedAt.getTime()) ? new Date() : closedAt;
};

export const MERCHANT_REGISTERED_TOPIC = 'merchant_registered_event';
export const INVOICE_CREATED_TOPIC = 'invoice_created_event';
export const SUBSCRIBED_TOPIC = 'subscribed_event';

/**
* Growth events only move PlatformDailyStats' "new X today" counters. The
* point-in-time totals they feed into (how many merchants exist, how many
* invoices are in each status) are counted live at request time off the
* existing tables, so nothing else needs recording here.
*/
export const handleMerchantRegistered = async (event: DecodedEvent): Promise<void> => {
const data = decodeMerchantRegisteredEventData(event.data);
await recordDailyStats(prisma, new Date(data.timestamp * 1000), { newMerchants: 1 });
};

export const handleInvoiceCreated = async (event: DecodedEvent): Promise<void> => {
// `InvoiceCreatedEvent` is the one growth event the contract emits without a
// timestamp field, so the day comes from the close time of the ledger that
// contained it. Using the indexing time instead would bucket a historical
// replay into whatever day the replay happened to run.
decodeInvoiceCreatedEventData(event.data);
await recordDailyStats(prisma, ledgerCloseTime(event), { newInvoices: 1 });
};
Comment thread
codebestia marked this conversation as resolved.

export const handleSubscribed = async (event: DecodedEvent): Promise<void> => {
const data = decodeSubscribedEventData(event.data);
await recordDailyStats(prisma, new Date(data.timestamp * 1000), { newSubscriptions: 1 });
};
Comment thread
codebestia marked this conversation as resolved.
45 changes: 45 additions & 0 deletions src/indexer/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,49 @@
import { registerEventHandler } from '../registry.js';
import { handleInvoicePaid, INVOICE_PAID_TOPIC } from './invoicePaid.js';
import { handleSubscriptionCharged, SUBSCRIPTION_CHARGED_TOPIC } from './subscriptionCharged.js';
import {
handleTicketPurchased,
handleTicketResold,
TICKET_PURCHASED_TOPIC,
TICKET_RESOLD_TOPIC,
} from './ticketing.js';
import {
handleInvoiceCreated,
handleMerchantRegistered,
handleSubscribed,
INVOICE_CREATED_TOPIC,
MERCHANT_REGISTERED_TOPIC,
SUBSCRIBED_TOPIC,
} from './growth.js';
import {
handleInvoicePartiallyRefunded,
handleInvoiceRefunded,
INVOICE_PARTIALLY_REFUNDED_TOPIC,
INVOICE_REFUNDED_TOPIC,
} from './refunds.js';

// Volume-moving events: they update MerchantAnalytics, TokenAnalytics and the
// protocol-wide PlatformDailyStats rollup.
registerEventHandler(INVOICE_PAID_TOPIC, handleInvoicePaid);
registerEventHandler(SUBSCRIPTION_CHARGED_TOPIC, handleSubscriptionCharged);
registerEventHandler(TICKET_PURCHASED_TOPIC, handleTicketPurchased);
registerEventHandler(TICKET_RESOLD_TOPIC, handleTicketResold);

// Growth events: they only move PlatformDailyStats' "new X today" counters.
registerEventHandler(MERCHANT_REGISTERED_TOPIC, handleMerchantRegistered);
registerEventHandler(INVOICE_CREATED_TOPIC, handleInvoiceCreated);
registerEventHandler(SUBSCRIBED_TOPIC, handleSubscribed);

// Refund events: they adjust the invoice only. Volume is deliberately not
// netted down — see applyInvoiceRefund.
registerEventHandler(INVOICE_REFUNDED_TOPIC, handleInvoiceRefunded);
registerEventHandler(INVOICE_PARTIALLY_REFUNDED_TOPIC, handleInvoicePartiallyRefunded);

// Intentionally unhandled, and left to log "no handler registered":
// - subscription_plan_created_event / event_created_event: growth events with
// no dedicated daily counter in PlatformDailyStats. Plan and event totals
// are point-in-time counts, and adding daily counters for them is a
// follow-up if a dashboard ever asks for the trend.
// - status and governance events (merchant_status_changed_event,
// role_granted_event, contract_paused_event, fee_set_event, ...): out of
// scope for analytics indexing.
6 changes: 4 additions & 2 deletions src/indexer/handlers/invoicePaid.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { applyInvoicePayment } from '../../services/invoice.services.js';
import { decodeInvoicePaidEventData, type DecodedEvent } from '../types.js';

// The `#[contractevent] InvoicePaidEvent` macro emits this first topic symbol.
export const INVOICE_PAID_TOPIC = 'InvoicePaid';
// Soroban's `#[contractevent]` macro publishes a single fixed first topic: the
// struct name in lower snake case. `InvoicePaidEvent` therefore arrives as
// "invoice_paid_event".
export const INVOICE_PAID_TOPIC = 'invoice_paid_event';

/**
* Keeps contract-specific payload normalization at the indexer edge; all
Expand Down
17 changes: 17 additions & 0 deletions src/indexer/handlers/refunds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { applyInvoiceRefund } from '../../services/invoice.services.js';
import {
decodeInvoicePartiallyRefundedEventData,
decodeInvoiceRefundedEventData,
type DecodedEvent,
} from '../types.js';

export const INVOICE_REFUNDED_TOPIC = 'invoice_refunded_event';
export const INVOICE_PARTIALLY_REFUNDED_TOPIC = 'invoice_partially_refunded_event';

export const handleInvoiceRefunded = async (event: DecodedEvent): Promise<void> => {
await applyInvoiceRefund(decodeInvoiceRefundedEventData(event.data), event.txHash);
};

export const handleInvoicePartiallyRefunded = async (event: DecodedEvent): Promise<void> => {
await applyInvoiceRefund(decodeInvoicePartiallyRefundedEventData(event.data), event.txHash);
};
8 changes: 8 additions & 0 deletions src/indexer/handlers/subscriptionCharged.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { applySubscriptionCharge } from '../../services/subscription.services.js';
import { decodeSubscriptionChargedEventData, type DecodedEvent } from '../types.js';

export const SUBSCRIPTION_CHARGED_TOPIC = 'subscription_charged_event';

export const handleSubscriptionCharged = async (event: DecodedEvent): Promise<void> => {
await applySubscriptionCharge(decodeSubscriptionChargedEventData(event.data), event.txHash);
};
17 changes: 17 additions & 0 deletions src/indexer/handlers/ticketing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { applyTicketPurchase, applyTicketResale } from '../../services/ticket.services.js';
import {
decodeTicketPurchasedEventData,
decodeTicketResoldEventData,
type DecodedEvent,
} from '../types.js';

export const TICKET_PURCHASED_TOPIC = 'ticket_purchased_event';
export const TICKET_RESOLD_TOPIC = 'ticket_resold_event';

export const handleTicketPurchased = async (event: DecodedEvent): Promise<void> => {
await applyTicketPurchase(decodeTicketPurchasedEventData(event.data), event.txHash);
};

export const handleTicketResold = async (event: DecodedEvent): Promise<void> => {
await applyTicketResale(decodeTicketResoldEventData(event.data), event.txHash);
};
1 change: 1 addition & 0 deletions src/indexer/poller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export async function tick(): Promise<void> {
topic: decodedTopic,
ledger: event.ledger,
txHash: event.txHash,
ledgerClosedAt: event.ledgerClosedAt,
data: decodedValue,
});

Expand Down
Loading
Loading