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
27 changes: 11 additions & 16 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **API Versioning & Lifecycle Management** ([#449](https://github.com/Nanle-code/stellar-dev-dashboard/issues/449)).
Comprehensive API versioning system with analytics, migration tools, and sunset policy enforcement.
- `api/routes/analytics.ts` — Admin endpoints for version usage metrics, deprecated route tracking, and adoption rates
- `api/routes/migration.ts` — Public endpoints for migration guides, compatibility checks, breaking changes, and sunset policy
- `api/utils/migrationTools.ts` — Migration utilities including version compatibility checking, breaking change tracking, and sunset policy definitions
- Enhanced `api/middleware/apiVersioning.ts` — Added real-time version tracking, sunset date enforcement with HTTP 410 responses, and per-endpoint usage analytics
- `docs/api/API_LIFECYCLE_MANAGEMENT.md` — Complete guide covering versioning strategy, backward compatibility, deprecation process, migration tools, analytics, and sunset policy
- Updated `docs/api/VERSION_HISTORY.md` — Detailed changelog of version 1.1.0 features and endpoints
- Updated `docs/api/API_VERSIONING.md` — Added references to lifecycle management documentation
- Version analytics tracking with endpoint-level granularity
- Programmatic migration guides accessible via REST API
- Automatic sunset enforcement (410 Gone after sunset date)
- Breaking changes documentation with impact levels
- 6-month minimum deprecation period with 30-day grace period
- Real-time adoption rate calculation across API versions

- **Cost attribution by application tag or memo prefix** ([#868](https://github.com/Nanle-code/stellar-dev-dashboard/issues/868)).
Attributes transaction fees and asset transfer volumes to developer-defined project tags for project budgeting and threshold alerts.
- `src/lib/costThresholdManager.ts` — `CostThresholdManager` implementation for tag definition, memo prefix and regex pattern matching, budget limits, volume tracking, threshold alerts (`ok`, `warning`, `exceeded`), JSON/CSV report exports, and SSR/unsupported environment fallbacks.
- `src/lib/analytics.ts` — integrated `costAttribution` calculation into `buildAnalyticsSnapshot()` and re-exported `CostThresholdManager`.
- `docs/features/COST_ATTRIBUTION_ANALYTICS.md` — feature documentation, usage examples, compatibility, security, and migration notes.
- `src/lib/__tests__/costThresholdManager.test.ts` — 13 unit tests covering primary flow, boundary cases (0 fee, exact threshold %, 100% budget cap), failure paths (invalid regex, NaN/negative fees, null inputs), and SSR/storage error handling.
- **Cohort retention views for account activity** ([#863](https://github.com/Nanle-code/stellar-dev-dashboard/issues/863)).
Provides cohort charts that group accounts by first-seen period (Day, Week, Month) and subsequent activity.
- `src/lib/cohortRetention.ts` — domain calculations for cohort retention matrices, period headers, summary stats, CSV/JSON exports, and graceful error handling.
- `src/components/dashboard/CohortRetentionView.tsx` — accessible UI view featuring cohort heatmap matrix table, line chart, controls, view mode toggles, and export triggers.
- `docs/features/COHORT_RETENTION_ANALYTICS.md` — comprehensive user-facing and developer documentation including compatibility, security, and migration guidance.
- **Pre-sign risk summary** ([#982](https://github.com/Nanle-code/stellar-dev-dashboard/issues/982)).
Every transaction is now parsed and described in plain language before it
reaches a wallet, so an operation that irreversibly changes an account cannot
Expand Down
29 changes: 29 additions & 0 deletions PR_DESCRIPTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
## Summary

Implements cost attribution by application tag or memo prefix for project budgeting (#868). Attributes transaction fees (in Stroops and XLM) and payment transfer volumes to developer-defined project tags (e.g. `billing`, `auth`, `nft-drop`, `defi-swap`) via literal memo prefixes (e.g., `[APP:billing]`, `BILL:`) or custom regex patterns.

- **Domain Library (`src/lib/costThresholdManager.ts`)**: `CostThresholdManager` implementation for tag definition, memo prefix and regex pattern matching, budget limits, volume tracking, threshold alerts (`ok`, `warning` >= 80%, `exceeded` >= 100%, `unbudgeted`), auto-discovery of embedded tags (`[APP:tag]`), JSON/CSV report exports, and graceful SSR/storage error handling.
- **Analytics Integration (`src/lib/analytics.ts`)**: Embedded cost attribution calculations into `buildAnalyticsSnapshot()` and re-exported `CostThresholdManager`.
- **Documentation**: User-facing & developer guide in [`docs/features/COST_ATTRIBUTION_ANALYTICS.md`](docs/features/COST_ATTRIBUTION_ANALYTICS.md) and changelog entry in `CHANGELOG.md`.

Closes #868

## How was this tested?

Ran unit tests:
`pnpm run test:unit src/lib/__tests__/costThresholdManager.test.ts` (13 passed)

- **Primary flow**: Verified adding/updating rules, attributing fees and payment volumes to configured tags by memo prefix, auto-discovering unbudgeted tag prefixes, calculating fee sums in Stroops and XLM, average fee calculations, and JSON/CSV report exporting.
- **Boundary cases**: Verified empty transaction list handling, exact warning threshold calculation (80.0%), exact 100% budget cap exceedance, zero-fee transactions, and case-insensitive memo matching.
- **Failure cases**: Verified `null` / `undefined` / non-array transaction inputs, malformed transaction objects with invalid fee strings (`"invalid_number"`, negative fees), malformed regex rules (unclosed brackets), throwing `localStorage` security/quota errors in restricted SSR/iframe sandboxes, and missing required rule properties.

## Merge requirements

A PR is merged only when **every** box below is true. See
[Merge requirements](https://github.com/Nanle-code/stellar-dev-dashboard/blob/master/docs/contributing.md#merge-requirements) for the full policy.

- [x] All required CI checks pass on the latest commit (not just an earlier push).
- [x] No required checks are failing, pending, or skipped — re-run or fix them; do not ask for a merge while any are outstanding.
- [x] The branch has no merge conflicts with the target branch (rebase or merge `master` if GitHub shows "This branch has conflicts").
- [x] Tests were added or updated for the change (primary flow, a boundary case, and a failure case).
- [x] Docs were updated where behaviour, configuration, or security posture changed.
97 changes: 97 additions & 0 deletions docs/features/COHORT_RETENTION_ANALYTICS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Cohort Retention Views for Account Activity

## Overview

Issue #863 introduces **Cohort Retention Views** for account activity in the Stellar Dev Dashboard analytics workspace.

This feature enables developers, node operators, and ecosystem analysts to group accounts by their first-seen period (Day, Week, or Month) and track their retention rates over subsequent periods.

---

## Features & Capabilities

1. **Cohort Heatmap Matrix Table**:
- Displays cohort start dates, initial cohort size (Period 0), and subsequent retention rates (% or account count).
- HSL-tailored color gradients indicating retention depth (Bright Teal/Cyan for 80-100%, Emerald Green for 60-79%, Amber for 40-59%, Orange for 20-39%, Purple for 1-19%).
- Accessible hover tooltips showing active account counts vs total cohort size.

2. **Retention Curve Visualization**:
- Interactive line chart tracking the aggregated average retention curve across all cohorts over time.

3. **Multi-Period Granularity**:
- Toggle between **Daily** (`day`), **Weekly** (`week`), and **Monthly** (`month`) cohort groupings.

4. **Activity Type Filtering**:
- Filter cohort activity by **All Activities**, **Payments**, **Smart Contracts** (Soroban), or **DEX Trades**.

5. **Data Exporting**:
- One-click CSV and JSON export options for offline reporting and data pipeline integration.

6. **Summary Metrics Dashboard**:
- Key indicators for Total Cohorts Tracked, Total Unique Accounts, Avg Period 1 Retention (+1 Wk/Day/Mo), Avg Period 4 Retention, and Best Performing Cohort.

---

## Architecture & File Structure

- **`src/lib/cohortRetention.ts`**: Pure TypeScript domain logic for calculating cohort retention matrices, periods, statistics, formatting, CSV/JSON exports, and input validation.
- **`src/components/dashboard/CohortRetentionView.tsx`**: React UI component rendering the cohort controls, summary metrics, heatmap matrix table, line chart, and export triggers.
- **`src/lib/__tests__/cohortRetention.test.ts`**: Automated unit tests covering primary calculation flows, boundary cases, and failure paths.
- **`src/components/dashboard/__tests__/CohortRetentionView.test.tsx`**: React component tests validating UI rendering, filter switching, view mode toggling, and export callbacks.
- **`src/routes/routes.ts`**: Registered route `/cohortRetention` under the `analytics` group.

---

## Compatibility Notes

- **Browser & Runtime Requirements**:
- Compatible with modern browsers supporting ES2022+ and HTML5 Canvas / SVG rendering (Recharts).
- Uses native UTC date calculations (`Date.UTC`) for standard time zone independence across regions.
- **SSR / Node & Test Environment Fallbacks**:
- File download handlers automatically detect browser environments (`window`, `URL.createObjectURL`) and degrade gracefully without throwing errors in Node.js, SSR, or JSdom test environments.
- **Node.js Policy**:
- Adheres to Node.js >= 22 engine policy as specified in `package.json`.

---

## Security Notes

- **PII & Address Privacy**:
- Stellar public keys (`G...`) are processed locally within the client memory. No private key, seed phrase, or unencrypted account metadata is recorded or exported.
- **Input Sanitization**:
- All account IDs and activity strings are trimmed and sanitized before insertion into cohort structures and CSV export rows to prevent CSV injection or cross-site scripting (XSS).
- **Error Boundaries & Circuit Breakers**:
- Calculation errors return typed result objects (`CohortRetentionResult`) with explicit error codes (`INVALID_INPUT`, `UNSUPPORTED_ENVIRONMENT`, `CALCULATION_FAILED`), preventing unhandled runtime exceptions from crashing the dashboard.

---

## Migration & Integration Guide

### Consuming the Cohort Library in Custom Components

```typescript
import { calculateCohortRetention } from './lib/cohortRetention';

const result = calculateCohortRetention(accountActivities, {
granularity: 'week',
activityFilter: 'all',
maxPeriods: 8,
});

if (result.ok) {
console.log('Cohort Rows:', result.data.cohorts);
console.log('Avg Period 1 Retention:', result.data.stats.avgPeriod1Retention);
} else {
console.error('Cohort Error:', result.error.message);
}
```

### Embedding the UI View

```tsx
import CohortRetentionView from './components/dashboard/CohortRetentionView';

export function MyAnalyticsTab() {
return <CohortRetentionView title="Account Retention" />;
}
```
69 changes: 69 additions & 0 deletions docs/features/COST_ATTRIBUTION_ANALYTICS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Cost Attribution by Application Tag & Memo Prefix (#868)

## Overview

The `CostThresholdManager` provides project budgeting, cost tracking, and alert threshold monitoring for Stellar transactions by attributing fees and transfer volumes to developer-defined application tags or memo prefixes.

Developers can categorize Stellar transaction fees and payment volumes by application feature (e.g., `billing`, `auth`, `nft-drop`, `defi-swap`, `governance`) using literal memo prefixes (e.g. `[APP:billing]`, `BILL:`, `PAY:`) or custom regular expression patterns.

---

## Key Features

1. **Tag-Based & Memo-Prefix Attribution**:
- Matches literal prefixes (e.g., `[APP:billing]`, `AUTH:`) or custom regex patterns (e.g., `^PROJ-[0-9]+`).
- Automatically discovers unbudgeted tag prefixes embedded in memos formatted like `[APP:tag]` or `TAG:tag`.

2. **Project Budgeting & Threshold Monitoring**:
- Configurable Stroops fee budget limits and transfer volume tracking per tag.
- Configurable warning threshold percentages (default: 80%).
- Dynamic budget status flags: `ok`, `warning` (>= 80%), `exceeded` (>= 100%), and `unbudgeted`.

3. **Export Capabilities**:
- Export attribution reports directly as formatted `JSON` or `CSV`.

4. **Environment Fallback & Fault Tolerance**:
- Graceful fallback when `localStorage` or browser storage APIs are unavailable (e.g. SSR, restricted cross-origin iframe, or private browsing mode).
- Safe parsing of non-numeric, `NaN`, or negative fee strings without crashing.
- Safe isolation for malformed regular expression rules.

---

## Developer Guidance & Usage

### Basic Usage

```typescript
import { getCostThresholdManager } from './src/lib/costThresholdManager'

const manager = getCostThresholdManager()

// Add a budget rule for the billing feature
manager.addRule({
tag: 'billing',
memoPrefix: '[APP:billing]',
budgetLimitStroops: 10_000_000, // 1 XLM budget
warningThresholdPercent: 80,
})

// Attribute transactions
const summary = manager.attributeTransactions(transactions)

console.log(`Total Attributed Fee: ${summary.totalAttributedFeeXlm} XLM`)
console.log(summary.tagBreakdown)
```

### Exporting Reports

```typescript
const csvData = manager.exportAttributionReport(summary, 'csv')
const jsonData = manager.exportAttributionReport(summary, 'json')
```

---

## Compatibility, Security, and Migration Notes

- **Compatibility**: Compatible with Node.js >= 22 and all modern browsers. Fully functional in SSR (Server-Side Rendering) contexts with in-memory rule fallback.
- **Security & Privacy**: Memo analytics processes metadata exclusively on the client side or in explicit service boundaries. Private keys, secret seeds, or sensitive payload data are never logged or exported.
- **Migration**: Zero breaking changes. `buildAnalyticsSnapshot()` in `analytics.ts` has been updated to include `costAttribution` in the snapshot response seamlessly.
Loading
Loading