Skip to content

Touli Platform — Unified Architecture Document

Version: 1.0
Date: June 2025
Status: Architecture baseline for client review and engineering kickoff
Audience: Product stakeholders, client sponsors, engineering leads, compliance reviewers


Document Control

FieldValue
ProductTouli — impact, challenges, and gifting platform
RepositoryNx monorepo (Express API, React Native mobile, shared libraries)
Target data storePostgreSQL
Related artifactsdocs/architecture/ packet, docs/touli-erd.md, docs/touli-erd-postgres.sql

This document consolidates the high-level design (HLD), detailed designs (DLDs), architecture decision records (ADRs), data model, API contracts, compliance controls, rollout plan, and gift-economy flows into a single client-shareable reference.


1. Executive Summary

Touli is a mobile-first platform that encourages positive real-world actions (“deeds”) through challenges, verified submissions, a points economy (Touli Points), badges, leaderboards, and a vendor marketplace for anonymous gifting. Users complete challenges, submit evidence, earn points when deeds are verified, and spend points on gifts for others.

The architecture is designed around five non-negotiable principles:

  1. Rules first, AI second, humans third — automated rules gate every submission before AI or manual review.
  2. Deterministic points — the points engine never calls AI; rewards are reproducible from configuration snapshots and ledger history.
  3. Privacy on chain — blockchain stores pseudonymous proofs only; no personally identifiable information (PII) on chain.
  4. Ledger as source of truth — wallet balances are projections; append-only ledger entries are authoritative.
  5. Reproducibility — every economically relevant decision can be audited from config + ledger.

The platform uses a hybrid stack: an Express/Nx API with PostgreSQL, background workers for verification, points, and blockchain anchoring, and a React Native (Expo) mobile app. AI vision (e.g., Gemini) assists verification but does not determine point amounts.

Current implementation status: Foundation is in place (monorepo, auth, mobile screen shells, basic user model). Domain modules for challenges, verification pipelines, points ledger, gifting, and blockchain anchoring are specified in this architecture and scheduled for phased delivery.


2. Product Vision and Scope

2.1 What Touli Delivers

CapabilityDescription
Onboarding & consentAge-appropriate flows, parental consent, privacy and permissions
ChallengesCurated and user-facing challenge catalog with categories and difficulty
Deed submissionPhoto/video evidence upload with metadata and anti-abuse checks
VerificationRules engine → optional AI vision → manual review when needed
Touli PointsEarn on verified deeds; spend in marketplace; full audit trail
Badges & leaderboardRecognition and social proof without exposing sensitive data
GiftingAnonymous or pseudonymous gift purchases using earned points
Vendor marketplaceThird-party catalog, fulfillment, and order lifecycle
Blockchain proofsPeriodic Merkle-root anchoring of verification outcomes on Polygon
Admin & trust opsManual review queues, configuration management, compliance tooling

2.2 Users and Roles

RolePrimary interactions
End user (mobile)Challenges, submissions, wallet, shop, gifts, profile
Parent/guardianConsent and age-gating where required
VendorCatalog and fulfillment (future portal)
Trust operatorManual review, escalation, abuse response
Platform adminConfiguration, feature flags, observability

2.3 Out of Scope (This Architecture Cycle)

  • Infrastructure-as-code provisioning scripts
  • Final vendor onboarding legal agreements
  • Production environment cutover runbooks (referenced in rollout section, not executed here)

3. System Context

3.1 Logical Architecture

┌─────────────────┐     ┌─────────────────┐
│  Mobile App     │     │  Admin Console  │
│  (React Native) │     │  (future)       │
└────────┬────────┘     └────────┬────────┘
         │                       │
         └───────────┬───────────┘

            ┌────────────────┐
            │  API Gateway   │
            │  (Express/Nx)  │
            └───────┬────────┘

     ┌──────────────┼──────────────┐
     ▼              ▼              ▼
┌─────────┐  ┌─────────────┐  ┌──────────┐
│Submission│  │  Read API   │  │  Auth    │
│ Service  │  │  (queries)  │  │  Service │
└────┬────┘  └──────┬──────┘  └────┬─────┘
     │              │              │
     └──────────────┼──────────────┘

            ┌────────────────┐
            │   PostgreSQL   │
            │   (primary)    │
            └───────┬────────┘

            ┌───────▼────────┐
            │  Event Bus /   │
            │  Job Queue     │
            └───────┬────────┘
     ┌──────────────┼──────────────┐
     ▼              ▼              ▼
┌──────────┐ ┌──────────┐ ┌──────────────┐
│Verification│ │ Points  │ │  Anchor     │
│ Worker     │ │ Worker  │ │  Worker      │
└─────┬──────┘ └────┬────┘ └──────┬───────┘
      │             │              │
      ▼             ▼              ▼
 Rules + AI    Pure engine    Merkle + Polygon

3.2 Trust Boundaries

ZoneComponentsData sensitivity
User zoneMobile clientDevice-local cache; tokens
Application zoneAPI, workersBusiness logic; pseudonymous IDs
Data zonePostgres, object storagePII, media, ledger
External zoneGemini, Polygon/Alchemy, push/emailProcessed under DPAs; no raw PII on chain

Mobile clients never talk directly to AI or blockchain providers. All external calls are server-side with policy enforcement.


4. Core Domain Flows

4.1 Deed Submission and Verification

States: draftsubmittedrules_passed | rules_failedai_reviewapproved | rejected | manual_review → terminal outcome.

Pipeline:

  1. User submits deed with media and challenge reference.
  2. Rules engine (deterministic): file type, size, duplicate hash, rate limits, challenge eligibility.
  3. If rules fail → reject with reason codes (no AI spend).
  4. If rules pass → vision adapter scores evidence against challenge criteria (confidence score).
  5. Routing by confidence:
    • High confidence → auto-approve path
    • Low confidence → manual review queue
    • Medium → policy-defined (may sample for review)
  6. On approval → emit deed.verified event for points worker.
  7. Media retention and deletion follow compliance lifecycle (see Section 8).

4.2 Points Attribution

Trigger: deed.verified event (and defined admin adjustments).

Process:

  1. Load active points config snapshot (versioned; immutable once referenced).
  2. Compute award from: base points, challenge multiplier, caps, cooldowns, streak bonuses.
  3. Write append-only ledger entry with idempotency key (deed_id + config_version).
  4. Project wallet balance asynchronously or synchronously per read consistency policy.
  5. Emit points.credited for notifications, badges, leaderboard projection.

Invariants: No AI in this path. Same inputs + same snapshot → same points every time.

4.3 Gifting and Marketplace

Earn points → Browse catalog → Select gift → Confirm spend
     → Ledger debit → Order created → Vendor fulfillment → Delivery status
  • Spending creates a ledger debit linked to order id (idempotent).
  • Gifter identity may be hidden from recipient per product rules.
  • Refunds and partial fulfillment reverse or adjust via compensating ledger entries.

4.4 Blockchain Anchoring

Purpose: Tamper-evident, public audit of that verified deeds occurred — without exposing who did what.

  1. Batch approved verification records into Merkle tree.
  2. Leaf = hash(pseudonymous_user_id, deed_id, outcome, timestamp_bucket, config_hash).
  3. Submit Merkle root to Polygon via Alchemy adapter.
  4. Store tx hash, block, batch id for proof retrieval API.
  5. Reconciliation job verifies on-chain root matches off-chain batch.

5. Data Architecture

5.1 Conceptual Entity Groups

DomainKey entities
IdentityUser, session, consent, permissions
ChallengesCategory, challenge, user enrollment, progress
SubmissionsDeed submission, media asset, verification result
PointsConfig snapshot, ledger entry, wallet projection
RecognitionBadge, user badge, leaderboard snapshot
CommerceVendor, catalog item, order, fulfillment event
GiftingGift intent, anonymity policy, delivery
ChainAnchor batch, Merkle leaf, chain transaction
OperationsManual review case, audit log, feature flag

Full entity-relationship detail: see docs/touli-erd.md.
Postgres-ready DDL: see docs/touli-erd-postgres.sql.

5.2 Schema Evolution: Current vs Target

AreaImplemented today (Sequelize)Target (Postgres architecture)
Usersusers, user_rolesapp_user with UUID, age, consent
Authauths, refresh_tokensuser_session, OAuth providers
ChallengesFull challenge domain tables
SubmissionsDeed + verification tables
PointsSnapshot + append-only ledger
Gifting / shopVendor, order, gift tables
BlockchainBatch + leaf + tx tables

Migration from current auth foundation to target schema is defined in touli-schema-delta-spec.md (additive phases, no big-bang cutover).

5.3 Ledger Design (Critical)

points_ledger_entry
  id, user_id, type (credit|debit|adjustment)
  amount, balance_after (optional projection field)
  reference_type, reference_id
  config_snapshot_id (for credits)
  idempotency_key UNIQUE
  created_at (immutable)

Wallet table is a materialized projection rebuildable from ledger. Never update ledger rows in place.


6. API and Event Contracts (Summary)

6.1 Representative REST Endpoints

MethodPathPurpose
POST/auth/login, /auth/refreshSession management
GET/challengesList active challenges
POST/deedsCreate submission
POST/deeds/:id/mediaUpload evidence
GET/walletBalance and recent ledger
GET/leaderboardRankings
POST/ordersSpend points / place gift order
GET/proofs/:batchIdMerkle proof for verification

Full OpenAPI-style contracts: touli-api-event-contracts.md.

6.2 Domain Events

EventProducerConsumers
deed.submittedSubmission serviceVerification worker
deed.verifiedVerification workerPoints worker, notifications
deed.rejectedVerification workerNotifications
points.creditedPoints workerBadges, leaderboard, push
points.debitedOrder serviceFulfillment, notifications
anchor.batch.sealedAnchor workerAudit, admin dashboard

All events carry correlation id, idempotency key, and schema version.


7. Architecture Decision Records (Summary)

ADRDecisionRationale
Rules-before-AIDeterministic gates precede any model callCost control, safety, explainability
Pure points engineNo ML in points calculationAuditability, regulatory clarity
Append-only ledgerNo in-place balance mutationFinancial-grade traceability
Pseudonymous anchoringHashed identifiers on chainPrivacy compliance
Worker-based asyncVerification/points/chain off API hot pathResilience and scale
Config snapshotsVersioned point rules at credit timeReproducible disputes
Postgres primaryRelational integrity for ledgerACID, mature ops
Polygon + AlchemyL2 anchoring with managed RPCCost vs. Ethereum L1

Full ADR texts: docs/architecture/adr/.


8. Compliance, Privacy, and Safety

8.1 Regulatory Themes

  • Age-appropriate design: consent flows, parental gates, minimized data collection for minors.
  • GDPR / data subject rights: export, erasure requests with ledger retention exceptions documented.
  • Media lifecycle: verification retention window, then secure deletion; thumbnails may outlive originals per policy.
  • AI transparency: users informed when AI assists verification; human appeal path for manual review cases.

8.2 Security Controls

ControlImplementation
AuthenticationJWT access + rotating refresh tokens, device binding
AuthorizationRole-based access; admin actions audited
EncryptionTLS in transit; encrypted object storage for media
Rate limitingPer-user and per-IP on submission endpoints
Abuse detectionDuplicate media hash, velocity limits, device signals
Audit loggingAdmin and economically sensitive actions immutable log

Detail: touli-compliance-controls.md.


9. Observability and Operations

ConcernApproach
MetricsSubmission rate, verification latency, review queue depth, points credits/sec
SLOsAPI p95 < 300ms reads; verification p95 < 5 min (excl. manual)
AlertingQueue backlog, anchor failures, ledger idempotency violations
RunbooksAI provider outage → rules-only degrade; chain outage → batch retry

10. Phased Delivery Plan

PhaseFocusExit criteria
A — Points foundationLedger, snapshots, idempotencyCalculation contract approved; schema delta signed off
B — Verification foundationRules engine, state machine, manual reviewSLA and reason codes approved
C — AI integrationVision adapter, labeling, fallbacksProvider contract and outage policy approved
D — Blockchain anchoringMerkle batches, Polygon adapterPrivacy and reconciliation approved
E — Operational hardeningSLOs, runbooks, compliance checkpointGo/no-go checklist green

Suggested architecture finalization (2 weeks): Week 1 — HLD alignment, verification + points DLDs, schema review. Week 2 — blockchain + compliance, risk workshop, freeze package.

Detail: touli-rollout-risk-readiness.md.


11. Risk Register (Top Items)

IDRiskMitigation
R1Points logic drift vs. product docsSnapshot versioning; single source of truth gate
R2Duplicate credits on retryIdempotency keys; unique constraints
R3Manual review backlogCapacity planning; degrade routing
R4AI cost overrunRules-first gating; confidence thresholds
R5PII leakage on chainPseudonymization review; pre-publish checklist
R6Schema migration painAdditive migrations; dual-write window if needed

12. Current Implementation Snapshot

12.1 Repository Structure

AreaStatus
Nx monorepoActive — shared libs, server, mobile
Mobile app (Expo)Screen shells: auth, onboarding, challenges, shop, gifts, profile
API serverExpress with auth routes (login, refresh, user CRUD foundation)
Data modelsSequelize: User, UserRole, Auth, RefreshToken
Architecture docsFull packet in docs/architecture/
Target ERD / SQLdocs/touli-erd.md, docs/touli-erd-postgres.sql

12.2 Gap to Target Architecture

The following are specified but not yet built in production code:

  • Challenge catalog and enrollment APIs
  • Deed submission and object storage integration
  • Verification worker pipeline (rules, AI, manual review)
  • Points engine and ledger tables
  • Marketplace, orders, and gifting flows
  • Badge and leaderboard projection jobs
  • Blockchain anchor worker and proof API
  • Admin console for trust operations

This gap is expected; the architecture packet defines the build order via Phases A–E.


13. Technology Stack

LayerChoice
MonorepoNx + Yarn workspaces
APINode.js, Express, Sequelize (migrating toward Postgres-native schema)
MobileReact Native, Expo, file-based routing
DatabasePostgreSQL (target)
QueueTBD — SQS, Redis/Bull, or cloud-native equivalent
Object storageS3-compatible for deed media
AIGemini (vision) via server adapter
BlockchainPolygon via Alchemy
CILint, test, type-check per app; mobile native builds

14. Go / No-Go Checklist (Architecture Freeze)

  • [ ] HLD and invariants accepted by client and engineering
  • [ ] Verification state machine and reason codes signed off
  • [ ] Points calculation contract and snapshot model signed off
  • [ ] Schema delta reviewed against ERD and migration plan agreed
  • [ ] API/event contracts baselined for MVP slice
  • [ ] Compliance controls mapped to features (consent, retention, DSAR)
  • [ ] Risk register owners assigned
  • [ ] Phase A kickoff date confirmed

15. Appendix — Reference Documents

DocumentLocation
Core HLDdocs/architecture/touli-core-hld.md
Verification DLDdocs/architecture/touli-verification-dld.md
Points DLDdocs/architecture/touli-points-dld.md
Blockchain DLDdocs/architecture/touli-blockchain-dld.md
Schema deltadocs/architecture/touli-schema-delta-spec.md
API & eventsdocs/architecture/touli-api-event-contracts.md
Compliancedocs/architecture/touli-compliance-controls.md
Rollout & risksdocs/architecture/touli-rollout-risk-readiness.md
Gift economy flowsdocs/architecture/touli-gift-economy-flowchart.md
Conceptual ERDdocs/touli-erd.md
Postgres DDL draftdocs/touli-erd-postgres.sql
Mobile dev setupdocs/mobile/setup-guide.md

16. Glossary

TermDefinition
DeedA user submission proving completion of a challenge action
Touli PointsPlatform currency earned by verified deeds and spent on gifts
Config snapshotImmutable version of point rules used at credit time
Ledger entryAppend-only financial record of point credit or debit
Anchor batchGroup of verification outcomes hashed into a Merkle root for chain
Trust operatorHuman reviewer for borderline or escalated submissions

End of document. For questions or architecture change requests, track via the project decision log and ADR process.