Skip to content
QuantSingularityPublic

About

ZK-powered synthetic asset liquidity engine with a FastAPI backend, cross-chain routing, and React/React Native UI.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

187 Commits

Folders and files

Repository files navigation

Fluxion

CI/CD Status License: MIT Python 3.11+ Node 20+

Fluxion is a synthetic asset liquidity engine: a FastAPI backend for portfolios, transactions, markets, risk, compliance, and ML-driven analytics, paired with a React web dashboard, a React Native (Expo) mobile app, Foundry-managed Solidity contracts with a Circom price-commitment circuit, and a PyTorch inference package (ml_models) that the backend uses for liquidity forecasting, risk scoring, and anomaly detection.

Fluxion HomePage

Table of Contents

Overview

Topic Summary
API FastAPI endpoints under /api/v1 for auth, users, portfolio, transactions, analytics, markets, compliance, risk, and ML.
ML The backend's ML gateway runs ml_models in-process, calls it as a separate HTTP service, or is disabled (ML_MODE). Models train on synthetic data at first start, and inputs are a simulated market snapshot.
Contracts Foundry-managed Solidity 0.8.19 contracts for synthetic assets, liquidity pools, liquidation, and governance, plus a Circom circuit and Groth16 verifier. They are deployed independently per network.
Clients A React web dashboard and a React Native mobile app, both talking to the same REST API.
Tests 203 backend, 65 ML model, 64 smart contract, 59 web, and 52 mobile tests. All five suites run in CI.

Architecture

flowchart TD
    web["web-frontend (React, Vite)"] -->|"HTTP/JSON"| api
    mobile["mobile-frontend (React Native, Expo)"] -->|"HTTP/JSON"| api
    api["FastAPI backend: /api/v1 (auth, users, portfolio, transactions, analytics, markets, compliance, risk, ml)"] --> db[("PostgreSQL")]
    api --> redis[("Redis")]
    api -->|"ML gateway: local, remote, or disabled"| ml["ml_models: liquidity, supply chain, risk, anomaly, compliance"]
    chain["Foundry contracts: SyntheticAssetFactory, LiquidityPoolManager, SyntheticLiquidationEngine, FluxionGovernanceToken, Groth16Verifier"]
Loading
Supporting service Image or build Host port Role
redis redis:7-alpine 6379 Cache and rate limiting
vault hashicorp/vault:1.15.4 8200 Secrets
ml-service code/ml_models/Dockerfile 8000 ML inference service, authenticated by an API key
blockchain trufflesuite/ganache 8545 Local chain
prometheus prom/prometheus:v2.49.1 9090 Metrics collection
grafana grafana/grafana:10.3.1 3001 Dashboards

These are defined in infrastructure/docker-compose.yml, which also defines the api and web-frontend services and the Elastic logging stack. See docs/ARCHITECTURE.md for detail.

Project Structure

Path Purpose
code/backend FastAPI application: routes, services, middleware, models, and tests
code/ml_models PyTorch inference package: models, training CLI, serving app, and tests
code/blockchain Foundry project: Solidity contracts, Circom circuit, and tests
web-frontend React (Vite) dashboard
mobile-frontend React Native (Expo) app
infrastructure Docker, Kubernetes, Terraform, Ansible, and monitoring configuration
scripts Setup, run, test, deployment, and monitoring scripts
docs Project documentation
.github CI/CD workflow and its documentation

Feature Status

Component Details
API FastAPI backend with ten route groups under /api/v1, plus /health, /health/detailed, and a Prometheus /metrics endpoint.
Auth bcrypt password hashing, JWT access and refresh tokens, TOTP-based MFA (pyotp), session management, and API key management. SECRET_KEY must be at least 32 characters, and a development default satisfies that check.
Portfolio and risk In-process Python logic for VaR, Expected Shortfall, Sharpe and Sortino ratios, max drawdown, beta, concentration and liquidity risk, stress testing, performance, and rebalancing recommendations.
Collateral engine Mint, burn, and liquidate logic with price-staleness checks and collateral-ratio calculations, run in-process by the backend.
Compliance KYC initiation, document and biometric submission, and compliance status, with audit and compliance middleware.
ML gateway /api/v1/ml routes for pool and asset risk, liquidity and supply-chain forecasts, risk assessment, transaction screening, and model training. The read-only market snapshot routes are open; status, the custom-data POST routes, and transaction screening need a signed-in user, and training needs an admin, super admin, or risk manager role. Modes: auto (remote if ML_SERVICE_URL is set, otherwise local), remote, local, and disabled.
ML models Bidirectional LSTM with attention (liquidity forecasting and risk scoring), a CNN-LSTM-attention model (supply-chain demand), an autoencoder plus Isolation Forest (anomaly detection), and a multi-label MLP (compliance).
Smart contracts SyntheticAssetFactory (Chainlink price feeds and the Any-API request pattern), FluxionLiquidityPoolManager, SyntheticLiquidationEngine, and FluxionGovernanceToken, on OpenZeppelin 4.9 and Solidity 0.8.19.
Zero-knowledge layer A Circom circuit (price_commitment.circom) with a matching Groth16Verifier.sol contract for private price commitments.
Web dashboard React app (JavaScript, Vite, Chakra UI, Ethers.js 6, Recharts) with Home, Dashboard, Pools (and pool creation), Synthetics, Analytics, Portfolio, Transactions, Settings, and authentication pages, plus an ML risk panel.
Mobile app React Native (Expo SDK 52) app with Home, Dashboard, Pools, Create Pool, Synthetics, Portfolio, Analytics, Settings, and authentication screens, using React Navigation and React Native Paper.
Guest session Both clients recognize a local demo session and keep working with placeholder data if the backend is unreachable.

Technology Stack

Area Technology
Blockchain Solidity 0.8.19, Foundry, OpenZeppelin 4.9, Chainlink contracts
Zero-knowledge Circom, a Groth16 verifier contract
Backend API Python 3.11+, FastAPI, Uvicorn, Gunicorn, Pydantic v2
Auth bcrypt (passlib), PyJWT, pyotp (MFA)
Data layer SQLAlchemy 2 (async), PostgreSQL (SQLite for tests), Redis
ML PyTorch, scikit-learn, pandas, NumPy, joblib
Observability prometheus-client, structlog, Sentry SDK
Web frontend React 18, Vite 5, Chakra UI, Ethers.js 6, Recharts, React Router
Mobile frontend React Native, Expo (SDK 52), React Navigation, React Native Paper
Infrastructure Docker, Docker Compose, Kubernetes, Terraform, Ansible
Monitoring Prometheus, Grafana, the Elastic stack (Elasticsearch, Kibana, Filebeat), HashiCorp Vault
CI/CD GitHub Actions
Testing pytest (backend and ML models), Foundry (contracts), Jest (web and mobile)

Installation and Setup

Prerequisites: Foundry, Python 3.11+, and Node.js 20+. Docker is optional.

git clone --recurse-submodules https://github.com/quantsingularity/Fluxion.git
cd Fluxion

# Smart contracts (clones the Solidity dependencies)
cd code/blockchain
forge install

# Backend (includes PyTorch for the in-process ML mode)
cd ../backend
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

# Web frontend
cd ../../web-frontend
npm install --legacy-peer-deps

# Mobile frontend
cd ../mobile-frontend
npm install --legacy-peer-deps

For an automated setup:

git clone --recurse-submodules https://github.com/quantsingularity/Fluxion.git
cd Fluxion
./scripts/setup_fluxion_env.sh
./scripts/run_fluxion.sh

Full, environment-specific instructions are in docs/INSTALLATION.md.

Running the Stack

# 1) Supporting services (from infrastructure/, Docker required)
docker compose up -d redis vault

# 2) Local chain (from code/blockchain)
anvil                              # http://127.0.0.1:8545

# 3) Backend (from code/backend, venv active)
DATABASE_URL="sqlite+aiosqlite:///./fluxion.db" uvicorn app.main:app --reload
                                   # http://127.0.0.1:8000, docs at /docs

# 4) Web dashboard (from web-frontend)
npm run dev                        # http://localhost:3000, proxies /api to :8000

# 5) Mobile app (from mobile-frontend)
npm start                          # press w for web, a for Android, i for iOS

DATABASE_URL defaults to a local PostgreSQL instance (postgresql+asyncpg://fluxion:fluxion@localhost:5432/fluxion); the SQLite URL above is a quick start. With the default ML_MODE=auto and no ML_SERVICE_URL, the backend loads ml_models in-process and trains any missing models from synthetic data in the background after startup. Set ML_MODE=disabled to turn the ML routes off, in which case they return 503.

To run the ML package as its own service instead (from code/):

cd code
PORT=8001 ML_SERVICE_API_KEY=change-me python -m ml_models.serving
# then start the backend with:
#   ML_MODE=remote ML_SERVICE_URL=http://localhost:8001 ML_SERVICE_API_KEY=change-me

The mobile app reads its API address from mobile-frontend/app.json (extra.apiBaseUrl, default http://localhost:8000). See docs/USAGE.md and docs/CONFIGURATION.md.

API Surface

Base URL http://localhost:8000. Interactive docs at /docs (Swagger) and /redoc.

Group Prefix Endpoints
Health /api/v1/health Basic, detailed, ready, and live checks (also /health at the site root)
Auth /api/v1/auth register, login, refresh, logout, me, mfa/setup, mfa/verify, mfa/disable, api-keys, sessions, and the password-reset flow
Users /api/v1/users me, me/preferences, me/sessions, and account deactivation
Portfolio /api/v1/portfolio List, {id}, {id}/performance, {id}/assets
Transactions /api/v1/transactions List and create, {id}, {id}/cancel
Analytics /api/v1/analytics overview, risk, compliance
Markets /api/v1/markets pools, synthetics, and assets, each with an {id} lookup
Compliance /api/v1 kyc/initiate, kyc/document, kyc/biometric, compliance/status
Risk /api/v1/risk assessment/{user_id}, monitor, alerts, report
ML /api/v1/ml status, risk/overview, risk/assess, pools/{pool_id}/risk, pools/{pool_id}/forecast, assets/{asset_id}/risk, supply-chain/forecast, transactions/screen, models/train

Full request and response shapes are in docs/API.md.

Testing

Suite Directory Tests Run locally
Backend code/backend 203 pytest
ML models code/ml_models 65 PYTHONPATH=.. pytest tests/
Contracts code/blockchain 64 forge test
Web web-frontend 59 npm test
Mobile mobile-frontend 52 npm test

Run each command from the directory shown. All five suites run in CI. The backend and ML suites need PyTorch installed. See CI/CD Pipeline.

CI/CD Pipeline

GitHub Actions (.github/workflows/cicd.yml) runs on pushes and pull requests to main and develop, and on manual dispatch. Every job after the first depends on Code Quality Checks, so the other eight run in parallel once formatting passes.

# Job Depends on What it does
1 Code Quality Checks None autoflake and black --check on Python, plus a repository-wide Prettier check (JS, TS, JSON, HTML, CSS, Markdown, Solidity, YAML)
2 Backend Test & Build Code Quality Checks Runs pytest with coverage, then builds and smoke tests the backend and ML service images, including the ML service's authentication and readiness behavior
3 ML Models Test & Validation Code Quality Checks Byte-compiles ml_models, verifies its public API and 21 modules import cleanly, and runs its tests with coverage on CPU-only PyTorch
4 Web-Frontend Test & Build Code Quality Checks npm ci, the Jest suite, the production Vite build, and a build upload
5 Mobile-Frontend Test & Build Code Quality Checks npm ci, the Jest suite with coverage, the Expo web export, and a bundle upload
6 Smart Contracts Compile & Test Code Quality Checks Installs the Foundry dependencies, compiles the contracts, runs forge test with a gas report, and uploads the build output
7 Docs Validation Code Quality Checks markdownlint, offline link and anchor checks, code-sample syntax checks, docs and scripts consistency checks, and an advisory external link check
8 Infrastructure Validation Code Quality Checks Terraform, Kubernetes manifest and environment-values validation, and Ansible checks, plus yamllint, Compose and Dockerfile checks, an image build, and a secret scan
9 Scripts Validation Code Quality Checks ShellCheck, syntax, shebang, and executable-bit checks on every shell script, plus a --help smoke test for the CLI scripts

Coverage reports are kept for 30 days and build artifacts for 7 days. The step-by-step breakdown of each job is in .github/readme/README.md.

Documentation

Document Contents
docs/README.md Documentation index
docs/ARCHITECTURE.md System architecture
docs/API.md REST API reference
docs/INSTALLATION.md Setup for all components
docs/CONFIGURATION.md Environment variables and config
docs/USAGE.md Running and using the platform
docs/CLI.md Helper scripts reference
docs/FEATURE_MATRIX.md Feature status, implemented vs planned
docs/TROUBLESHOOTING.md Common issues and fixes
docs/CONTRIBUTING.md Contribution guide
docs/examples/liquidity_provision.md Example: providing liquidity to pools

Contributing

See docs/CONTRIBUTING.md.

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

ZK-powered synthetic asset liquidity engine with a FastAPI backend, cross-chain routing, and React/React Native UI.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Used by

Contributors

Languages