-
Notifications
You must be signed in to change notification settings - Fork 18
feat: analytics indexing and admin analytics endpoints #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
codebestia
merged 7 commits into
ShadeProtocol:main
from
G-ELM:feat/analytics-indexer-and-admin-endpoints
Aug 21, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c979343
feat(db): add PlatformDailyStats daily rollup model
G-ELM 000d2e4
fix(indexer): subscribe to the contract's real event topics
G-ELM 58e31ff
feat(analytics): add the shared analytics projection service
G-ELM 0eddb1f
feat(indexer): keep analytics current from payment, growth and refund…
G-ELM cdd7a7d
feat(admin): add read-only analytics endpoints
G-ELM 4dd9ec9
fix(analytics): correct refund totals and bucket invoice creation by …
G-ELM 8bf3945
Merge branch 'main' into feat/analytics-indexer-and-admin-endpoints
codebestia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
18 changes: 18 additions & 0 deletions
18
prisma/migrations/20260821120000_add_platform_daily_stats/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| }; | ||
|
|
||
| export const handleSubscribed = async (event: DecodedEvent): Promise<void> => { | ||
| const data = decodeSubscribedEventData(event.data); | ||
| await recordDailyStats(prisma, new Date(data.timestamp * 1000), { newSubscriptions: 1 }); | ||
| }; | ||
|
codebestia marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.