Skip to content

Repository files navigation

TraceRoot — "Trust from the Source"

QR + GPS cryptographic supply chain tracking for Sri Lankan agriculture and artisan goods. Farmers and artisans register batches with signed provenance and GPS; every handoff is ledgered; consumers scan a QR code for full chain-of-custody, price history, Ask AI, and micro-tips.

On top of the ledger sits a suite of role-specific AI agents: conversational Sinhala/Tamil onboarding for farmers who cannot fill forms, fair-price advice before a farmer accepts an offer, evidence-backed fraud investigation for admins, destination-by-destination export compliance review, and trilingual product storytelling. Every agent is backed by deterministic computation, so all of them keep working with no LLM configured.

Distribution: the complete source is submitted as a ZIP archive, not a public repository. Extract it and run the commands below from the extracted project root.


Tech stack

Layer Technology Role
Web / mobile UI React 18, TypeScript, Vite, Tailwind CSS v4, React Router, Leaflet, Capacitor Role dashboards, QR scan, maps, Android APK shell
Core API Python FastAPI, SQLAlchemy, JWT (OAuth2 password flow), ECDSA (cryptography), QR (qrcode) Auth, products, transfers, tips, media, notifications
ML service FastAPI, scikit-learn IsolationForest, NumPy Transfer anomaly scoring (quantity / velocity / markup)
Data store SQLite by default (Postgres-ready DATABASE_URL) Users, products, transfer logs, tips, audits, market reference prices
AI assistant Google Gemini (optional) → local Ollama → deterministic templates Product Q&A grounded in ledger data
Agent runtime Shared provider chain + tool-registry ReAct loop (core-api/services/agent_runtime.py) Powers the five role agents; every one degrades to templates
Localisation LanguageContext + lib/translations.ts (en / si / ta) Agent output and key UI copy in English, Sinhala, Tamil
Smart contracts Solidity (TraceRootRegistry.sol, TraceRootTipping.sol) on Polygon Amoy (optional wiring) On-chain registry / tip split (contracts present; live RPC optional)
DevOps Docker Compose (build from source); GitHub Actions → private container registry Local full stack + our internal image pipeline

Deployment details

Local (recommended for judges)

Unzip the submitted archive, cd into the project root, then run three processes — ML is optional (API falls back to rule-based scoring):

# Terminal 1 — Core API
cd core-api && python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8000 --reload

# Terminal 2 — Web app
cd web-app && npm install && npm run dev
# http://localhost:3000  (Vite proxies /api → :8000)

# Terminal 3 — ML (optional)
cd ml-service && python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8001

Docker (build from source)

cp .env.example .env   # set JWT_SECRET, optional GEMINI_API_KEY
docker compose up --build

Frontend → http://localhost:3000 · API → http://localhost:8000 · ML → http://localhost:8001

Everything builds from the files in the archive — no registry access needed.

Production-style (our private registry)

docker-compose.ghcr.yml and .github/workflows/ci.yml are included to show the deployment pipeline we use internally: CI builds traceroot-core-api, traceroot-ml-service, and traceroot-frontend images and pushes them to a private container registry, which a server then pulls. It requires registry credentials, so it is not part of the evaluation path — use the Docker build above.


Architecture / system overview

flowchart TB
  subgraph Clients
    WEB[React Web App<br/>Farmer · Middleman · Retailer<br/>Exporter · Consumer · Admin]
    APK[Capacitor Android<br/>GPS + Camera QR]
  end

  subgraph Backend
    API[core-api :8000<br/>FastAPI · JWT · ECDSA · QR · Tips]
    AG[agents<br/>Onboarding · Fair Price · Anomaly<br/>Export Compliance · Story]
    ML[ml-service :8001<br/>IsolationForest + rules]
    DB[(SQLite / Postgres)]
    UP[Upload volume<br/>product media]
  end

  subgraph Optional
    GEM[Gemini API]
    POLY[Polygon Amoy<br/>Registry + Tipping contracts]
  end

  WEB --> API
  APK --> API
  API --> AG
  AG --> DB
  API --> DB
  API --> UP
  API -->|anomaly eval| ML
  AG -.->|optional| GEM
  API -.->|optional anchors| POLY
Loading

Short explanation: Actors use one React UI (or Capacitor APK). The FastAPI gateway owns identity, GPS validation, cryptographic registration, QR generation, transfer/subdivision, tipping, and provenance queries. Suspicious transfers are scored by a decoupled ML microservice; if that service is down, the API uses a local rule fallback so demos never hard-fail. The agent layer reads the same ledger through plain SQL tools and only calls a model to phrase results — Gemini when keyed, local Ollama if present, otherwise hand-written templates. Solidity contracts and Polygon RPC are optional anchors — the working prototype uses a durable signed ledger in SQL with blockchain-style tx hashes.

Agent suite

Agent Role What it does Deterministic backbone
Farmer Onboarding Farmers Registers a producer by conversation in Sinhala, Tamil, or English instead of a form; optional voice input Ordered slot filler with validators; the model can never write an invalid field
Fair Price Advisory Farmers Judges whether a sale offer is fair before the farmer accepts it Verdict from ±15% against the 30-day reference median; the model only writes negotiating advice
Anomaly Investigation Admins Turns an ML flag into an evidence-backed report with recommended actions Rule engine owns severity and the action list; the model only writes prose
Export Compliance Exporters Reviews provenance against destination import rules and drafts the paperwork Requirement matcher across 4 destinations; 4 documents generated regardless of the model
Product Story Farmers & artisans Writes a product narrative in English, Sinhala, and Tamil from GPS, crop history, and producer profile Template composition from ledger facts

Endpoints live under /api/agents/* (core-api/routes/agents.py); every response carries an llm field of gemini, ollama, or template so the degraded path is visible.


Technical challenges & creative solutions

1. ML service must not block the core demo path

Heavy IsolationForest scoring and cold starts would stall farmer/middleman transfers if in-process. We split ML into ml-service/ and call it over HTTP from core-api/routes/products.py, with an explicit local rule-based fallback when the service is unreachable so provenance flows stay live in hackathon conditions.

2. Trustworthy GPS without punishing map-only demos

Field fraud needs fresh device GPS; judges and desktop demos often use a map picker. core-api/services/gps_validation.py enforces Sri Lanka bounds, stale-capture windows, and accuracy caps for device proofs, while still accepting map-sourced origins for farmers and fallbacks for consumer retail orders — balancing anti-spoofing with usability (web-app/src/hooks/useGeolocation.ts, Capacitor geolocation).

3. Provenance Q&A that does not hallucinate past the ledger

A free-form LLM can invent certifications. core-api/routes/ai.py runs a ReAct-style tool loop (get_batch_status and related lookups) so answers are grounded in transfer logs and product metadata; Gemini is optional, and the UI can surface agent thoughts (web-app/src/components/ai/TraceAIAssistant.tsx).

4. Proportional tips without requiring live chain settlement on day one

On-chain tip splits are ideal but RPC/keys are flaky in demos. Tip math mirrors the Solidity design (60/20/20-style splits) in core-api/routes/tips.py against an in-app consumer wallet (LankaQR/card top-up UX), while contracts/TraceRootTipping.sol keeps the same policy ready for Amoy when addresses are configured.

5. Agents that must not become a single point of failure

An agent that returns nothing without an API key is a liability in a hackathon room with no internet. Every agent computes its result deterministically first and calls a model only to phrase it: the fair-price verdict comes from a median comparison, anomaly severity from a rule engine, compliance status from a requirement matcher, and onboarding from an ordered slot filler. With GEMINI_API_KEY unset and no Ollama running, all five still return HTTP 200 with verdicts, severities, gaps, documents, and all three story languages populated — only the prose falls back to hand-written templates. The Sinhala and Tamil fallback strings are human-written rather than machine-translated, because small local models produce poor Sinhala and those strings are the primary path for anyone running Ollama.

6. Fraud recommendations a human can safely act on

The worst failure mode in this project is an admin quarantining a batch because a model invented a reason. So the Anomaly Investigation agent inverts the usual arrangement: a rule engine owns the severity and maps fired rules to a fixed action list, and the model is demoted to writing the report body under an explicit instruction not to add, remove, or reorder findings. Recommended actions are surfaced as buttons that still require a human click (web-app/src/components/admin/AnomalyInvestigationSandbox.tsx).

Calibrating those rules against real seed data mattered more than picking them. A 50 km GPS deviation threshold sounds strict until you notice that routine Matale→Colombo retail distribution is already ~115 km on a ~430 km island; likewise, flagging a producer whose batch type differs from their declared primary crop punishes every farmer who grows more than one thing. Both now trigger on genuine signals — cross-island movement, and a batch type the producer has never registered before.

7. Honest compliance rather than reassuring compliance

An export agent that reports "ready to ship" because it has no contrary evidence would be actively dangerous. Any requirement resting on data TraceRoot does not hold — MRL and aflatoxin lab reports, Lion Logo licences, Halal certification — is reported MISSING with a concrete remedy, never MET. Only Certificate of Origin and phytosanitary drafts can reach MET, and only when origin GPS validates inside Sri Lanka, the producer is admin-verified, and the custody chain is clean. The Provenance & Traceability Annex is the one document generated entirely from TraceRoot's own data, which is exactly where the platform has something a paper trail does not.


Scope Delivered

Fully implemented

  • Multi-role auth (Farmer, Middleman, Retailer, Exporter, Consumer, Admin) with JWT and seeded demo users
  • Producer registration + admin verification / audit UI
  • Batch registration, QR labels, GPS-pinned origin, media attachments
  • Role-based transfers, lot subdivision, retail listing, consumer scan + provenance timeline + Leaflet route map
  • Exporter portal: direct sourcing from farmers or middlemen, compliance review, document generation
  • ML anomaly evaluation + admin anomaly / ledger dashboards
  • Ask AI (ReAct tools + optional Gemini)
  • Five role agents — Farmer Onboarding, Fair Price Advisory, Anomaly Investigation, Export Compliance, Product Story — all functional with no LLM configured
  • Sinhala / Tamil / English language switching for agent output, persisted per browser
  • Consumer tip wallet, proportional tip split, discover / cart / orders flows
  • Notifications for handoffs
  • Docker Compose build, CI image pipeline, Capacitor mobile path

Partially implemented

  • Polygon / Solidity wiring — contracts exist and env slots (POLYGON_RPC_URL, registry/tipping addresses) are present; production path still uses SQL ledger hashes unless live contracts are configured
  • #VisitSriLanka layer — region tips and cultural copy are embedded in provenance/AI responses; not a full tourism CMS
  • Bank settlement — tip balances and bank fields exist; monthly real bank payout is simulated, not integrated with a live bank API
  • Market price feed — the Fair Price agent reads a seeded 90-day market_prices table with realistic farm-gate LKR anchors per crop, clearly labelled as reference data in the UI; it is not wired to a live commodity feed such as the Colombo Tea Auction or Dambulla DEC
  • Voice onboarding — the onboarding agent is conversational and trilingual by default, with Web Speech recognition and read-aloud added where the browser supports it; the mic is hidden entirely on browsers that do not
  • UI localisation — agent output and the multilingual surfaces are translated; the wider dashboard chrome remains English

Omitted (with justification)

  • Full Flutter rewrite — React + Capacitor delivers iOS/Android GPS/camera without maintaining a second codebase under hackathon time
  • MongoDB / Redis / S3 production stack — Compose stubs exist historically; SQLite + local uploads keep zero-config judging viable
  • OAuth social login / Stripe Connect — OAuth2 password + JWT and in-app tip wallet cover the demo contract without third-party payment KYC

Known limitations / setup quirks

  • First API boot seeds traceroot.db; delete the DB file to re-seed cleanly.
  • Without GEMINI_API_KEY, Ask AI and all five agents still run — verdicts, severities, compliance gaps, documents, and all three story languages are computed without a model, and only the prose is templated. Each agent response carries "llm": "gemini" | "ollama" | "template" so you can see which path ran.
  • Market reference prices are seeded demo data, not a live feed; the Fair Price panel says so on screen.
  • Anomaly severity and export compliance status come from rule engines, not the model — an LLM cannot upgrade a severity or mark a missing lab report as satisfied.
  • Voice input needs Chrome-family webkitSpeechRecognition; the mic button is hidden where unsupported. Most desktop browsers ship no si-LK / ta-LK synthesis voice, so read-aloud hides itself there too — Android Chrome is the intended target.
  • ML service optional: expect rule-based anomaly reasons if :8001 is down.
  • Camera QR scan and GPS capture need a secure origin. localhost is fine, but any off-machine/phone demo must be served over HTTPS — run ngrok http 3000, add the tunnel host to allowedHosts in web-app/vite.config.ts, and set PUBLIC_WEB_URL to the HTTPS URL so generated QR codes resolve.
  • Phone demos over LAN must use the machine IP in VITE_API_URL, not localhost (see Docs/MOBILE_APK.md).
  • Default JWT secret in examples must be changed for any public deploy (.env.example).
  • Cleartext HTTP is enabled for Capacitor local testing only — use HTTPS in production.
  • Smart-contract addresses default to zero address until you deploy and set env vars.

Demo login

Password for all seeded accounts: traceroot123

Role Usernames
Farmer aruna, menaka, suresh
Middleman lanka_logistics
Retailer arpico
Exporter ceylon_exports
Consumer consumer1
Admin admin

Suggested demo flow

  1. Onboarding agent — on /register, switch to Talk to me and pick සිංහල; answer the spoken/typed prompts, mark the farm on the map, and the agent hands a completed draft to the normal register call
  2. Farmer — register a batch → Generate story for English/Sinhala/Tamil copy → QR
  3. Middleman — buy/subdivide (e.g. batch #1001)
  4. Farmer — on an incoming purchase request, hit Check if this price is fair → verdict, reference band, suggested floor
  5. Retailer — purchase + publish listing
  6. Consumer — scan → provenance → Ask AI → tip
  7. Exporter — sign in as ceylon_exports, source a batch, then run a compliance review against the EU and download the Provenance Annex
  8. Admin — ledger + anomaly views → Run agent investigation on a flagged handoff → approve a recommended action

The seeded ledger is deliberately clean (all 24 handoffs GREEN), so the admin anomaly list starts empty. To demo step 8, first make a handoff that trips the ML thresholds — a steep price markup, or a quantity or transit-velocity jump — then investigate the resulting flag.


Project structure

TraceRoot/
├── core-api/              FastAPI gateway + SQLite
├── ml-service/            IsolationForest anomaly engine
├── web-app/               React + TypeScript + Capacitor
├── contracts/             Solidity (Polygon)
├── Docs/                  Extra guides (APK, proposal notes)
├── docker-compose.yml     Local full stack
├── docker-compose.ghcr.yml  Private-registry deploy (team use)
└── .env.example           Server secrets template

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages