> ## Documentation Index
> Fetch the complete documentation index at: https://docs.learnway.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Audit Trails & System Logging

> Multi-layered auditing architecture in LearnWay: Admin audit logs, on-chain transaction tracking, reward ledgers, payment webhooks, AI interaction audits, and Sentry observability.

# Audit Trails & System Logging

LearnWay maintains a multi-layered, immutable audit trail spanning administrative actions, blockchain execution, financial payments, gamification rewards, AI interactions, and system errors.

***

## Auditing Architecture Overview

```mermaid theme={null}
graph TD
    subgraph AuditDomains["📋 Specialized Audit Trails"]
        AdminAudit["🏛️ Admin Activity Log<br/>(admin_audit_logs)"]
        BlockchainAudit["⛓️ Blockchain Tx & Event Log<br/>(blockchain_transactions)"]
        RewardAudit["🎮 Reward & State Log<br/>(reward_transactions)"]
        PaymentAudit["💳 Financial & Webhook Log<br/>(payment_transactions)"]
        AIAudit["🤖 AI Interaction & Accuracy Log<br/>(ai_lesson_requests)"]
        ErrorAudit["🚨 Sentry Distributed Tracing<br/>(Error & Latency Tracing)"]
    end

    subgraph StorageEngines["💾 Persistence & Correlation"]
        PostgreSQL[("PostgreSQL Audit Store")]
        OnChainL2[("Lisk L2 Blockchain")]
        SentryDashboard["Sentry Monitoring"]
    end

    AdminAudit --> PostgreSQL
    RewardAudit -->|Correlates with TxHash| BlockchainAudit
    BlockchainAudit --> PostgreSQL
    BlockchainAudit -.->|On-Chain Mirror| OnChainL2
    PaymentAudit --> PostgreSQL
    AIAudit --> PostgreSQL
    ErrorAudit --> SentryDashboard
```

***

## 1. Administrative Action Auditing (`AdminAuditLog`)

Every administrative operation modifying curriculum, users, translation, or financial state is persisted to the `admin_audit_logs` table:

```typescript theme={null}
// PostgreSQL Table: admin_audit_logs
@Entity({ name: 'admin_audit_logs' })
@Index(['actorId', 'createdAt'])
export class AdminAuditLog extends BaseEntity {
  @Column({ name: 'actor_id' })
  actorId!: string;

  @Column({ name: 'actor_email' })
  actorEmail!: string;

  @Column({ name: 'actor_name', nullable: true })
  actorName?: string;

  @Column()
  action!: string; // e.g. CREATE_COURSE, UPDATE_QUESTION, BAN_USER

  @Column({ name: 'target_type', nullable: true })
  targetType?: string; // e.g. Course, User, TranslationJob

  @Column({ name: 'target_id', nullable: true })
  targetId?: string;

  @Column({ type: 'text', nullable: true })
  details?: string; // Serialized JSON of parameters & modified diffs

  @Column({ name: 'ip_address', nullable: true })
  ipAddress?: string; // Originating client IP
}
```

***

## 2. Blockchain & Smart Contract Transaction Auditing

All on-chain transactions submitted by the relayer (`learnway-transaction-processor`) to `LearnWayManager.sol` on Lisk L2 are tracked in `blockchain_transactions`:

| Field                           | Type                       | Description                                                                      |
| :------------------------------ | :------------------------- | :------------------------------------------------------------------------------- |
| `transactionHash`               | `string` (Indexed, Unique) | Lisk L2 on-chain transaction hash                                                |
| `fromAddress`                   | `string`                   | Relayer KMS / Server signer address                                              |
| `toAddress` / `contractAddress` | `string`                   | Target smart contract (e.g. `LearnWayManager.sol`)                               |
| `methodName`                    | `string`                   | Smart contract method invoked (`completeLesson`, `mintBadge`, `mintCertificate`) |
| `parameters`                    | `jsonb`                    | Serialized input arguments                                                       |
| `status`                        | `enum`                     | `PENDING`, `SUBMITTED`, `CONFIRMED`, `FAILED`                                    |
| `gasUsed` / `gasPrice`          | `bigint` / `decimal`       | Exact gas metrics for accounting                                                 |
| `blockNumber` / `confirmations` | `bigint` / `int`           | Settlement block height and confirmation count                                   |
| `error`                         | `string`                   | Error trace if transaction reverted or required gas escalation                   |

***

## 3. Reward & Gamification Ledger Auditing (`RewardTransaction`)

Every XP and Gem state change is recorded in `reward_transactions` with a direct cryptographic correlation link to Lisk L2:

```typescript theme={null}
// PostgreSQL Table: reward_transactions
@Entity({ name: 'reward_transactions' })
@Index(['userId', 'createdAt'])
@Index(['transactionType', 'createdAt'])
@Index(['processingStatus', 'createdAt'])
@Index(['blockchainBatchId'])
export class RewardTransaction extends BaseEntity {
  @Column()
  userId!: string;

  @Column({ type: 'enum', enum: RewardTransactionType })
  transactionType!: RewardTransactionType; // DAILY_CLAIM, LESSON_COMPLETE, BATTLE_WIN, CONTEST_PRIZE

  @Column({ type: 'int' })
  amount!: number;

  @Column({ type: 'text', nullable: true })
  reason?: string;

  @Column({ type: 'enum', enum: TransactionProcessingStatus })
  processingStatus!: TransactionProcessingStatus; // PENDING, PROCESSING, COMPLETED, FAILED

  @Column({ type: 'varchar', nullable: true })
  blockchainTxHash?: string; // Verifiable on-chain transaction hash on Lisk L2

  @Column({ type: 'timestamp', nullable: true })
  blockchainProcessedAt?: Date;

  @Column({ type: 'int', default: 0 })
  retryCount!: number;
}
```

***

## 4. Payment & Financial Webhook Auditing

All fiat on-ramp orders and app store subscriptions are audited in `payment_transactions`, `fonbnk_orders`, and `revenuecat_webhook_events`:

* **Full Financial Metrics**: Tracks `cryptoAmount`, `cryptoCurrency` (USDT/fUSD), `fiatAmount`, `fiatCurrency`, `exchangeRate`, and payout channels (mobile money / airtime).
* **Raw Webhook Verification**: Inbound webhook payloads from Fonbnk and RevenueCat are stored with HMAC-SHA256 signature verification logs to prevent replay attacks and aid payment reconciliation.

***

## 5. AI Interaction & Safety Auditing (`AiLessonRequest`)

Every student question and Google Gemini response is audited in `ai_lesson_requests` and `ai_analytics_logs`:

* **Parameters Audited**: `userId`, `lessonId`, `courseId`, `promptType`, `customQuestion`, `response`, `latencyMs`, `status` (`success`, `rejected`, `timeout`, `error`), and `errorCode`.
* **Accuracy & Feedback Scoring**: Captures user ratings (`thumbs_up` / `thumbs_down`) to track `feedbackPositiveRate` across 24h, 7d, and 30d sliding windows.
* **Prompt Versioning**: Emits `promptVersion` to benchmark output quality across prompt iterations.

***

## 6. Real-Time Distributed Error Monitoring (Sentry)

* **Integration**: Initialized in `src/instrument.ts` via `@sentry/nestjs` before application bootstrap.
* **Scope**:
  * Captures unhandled HTTP exceptions, WebSocket disconnections, and RPC provider failures.
  * Injects request breadcrumbs, user IDs (pseudonymous), and execution environment tags for rapid debugging.
