games_app/README.md
2026-09-23 16:28:14 +02:00

275 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Tloto
**Tloto** is an online prediction games platform (web + mobile) where players use **cryptocurrencies** as the payment method. The stack includes a crypto wallet layer (**USDT TRC20**, **TRX**, **USDC Polygon**) managed by the platform, ready for game integration.
## Monorepo layout
| Folder | Role |
|--------|------|
| `backend/` | Node.js API (auth, wallet, ledger, admin, games-ready) |
| `prediqo_mobile/` | Flutter mobile app (play + wallet) |
| `prediqo_web/` | React web app (platform admin + player experience) |
## Architecture
- **Mobile**: Flutter (`prediqo_mobile`) — clean architecture, BLoC, Dio, secure storage
- **Web**: React + Vite (`prediqo_web`) — admin modules today; player/games modules planned
- **Backend**: Node.js + TypeScript + Express
- **Database**: PostgreSQL (users, wallets, ledger, transactions, audit logs)
### Features
- **User management**: Registration, login, JWT + refresh tokens, 2FA (TOTP)
- **HD wallet**: BIP39/BIP44; unique deposit address per user per asset
- **Ledger**: Internal ledger as source of truth; blockchain used for confirmation only
- **Deposits**: Monitoring with configurable confirmations (TRON: 20, Polygon: 64)
- **Withdrawals**: Hot wallet signing, balance lock, optional 2FA
- **Security**: AES-256 for private keys, rate limiting, audit logs
---
## Backend
### Prerequisites
- Node.js 18+
- PostgreSQL
### Setup (local)
```bash
cd backend
cp .env.example .env
# Edit .env: DATABASE_URL, JWT_SECRET, ENCRYPTION_KEY (32-byte hex), PLATFORM_MNEMONIC (24-word BIP39)
npm install
npm run migrate
npm run dev
```
**Important:** The `.env` file can be in `backend/` or the repo root; both are loaded. `DATABASE_URL` must match your PostgreSQL user and password.
**If you get "password authentication failed" (local PostgreSQL):**
- Use the same user/password you use to log in to PostgreSQL (often user `postgres` and the password you set during install).
- If your password contains special characters (`@`, `#`, `%`, `:`, `/`), URL-encode them in `DATABASE_URL` (e.g. `@` → `%40`, `#` → `%23`).
- Test the connection: `npm run db:test` (from `backend/`). Then try: `psql -U postgres -d crypto_wallet -h localhost` and enter your password to confirm it works.
Example `backend/.env`:
```
DATABASE_URL=postgresql://user:password@localhost:5432/crypto_wallet
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
PLATFORM_MNEMONIC=your twenty four word mnemonic phrase here ...
```
**PLATFORM_MNEMONIC:** Must be a valid BIP39 phrase (12 or 24 words from the [BIP39 English wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt)). Do not use the placeholder; generate one once and keep it secret. Example (from project root): `cd backend && node -e "console.log(require('bip39').generateMnemonic(256))"` — then put the output in `.env` as `PLATFORM_MNEMONIC=word1 word2 ... word24`.
API runs at `http://localhost:4000`. Prefix: `/api/v1`.
### Environment
| Variable | Description |
|--------|-------------|
| `DATABASE_URL` | PostgreSQL connection string |
| `JWT_SECRET` | Secret for JWT (min 32 chars) |
| `ENCRYPTION_KEY` | 32-byte hex (64 chars) for AES-256 |
| `PLATFORM_MNEMONIC` | BIP39 mnemonic (12 or 24 words) for HD wallet; must be from the standard wordlist (see below) |
| `TRON_NODE_URL` | TronGrid API URL |
| `POLYGON_RPC_URL` | Polygon RPC URL |
| `USDC_POLYGON_CONTRACT` | USDC contract on Polygon |
| `USDT_TRC20_CONTRACT` | Optional override for USDT TRC20 (e.g. testnet token) |
### Testing with testnets (no real crypto)
You can run the backend against **testnets** to test deposits and withdrawals with free test tokens, then switch back to mainnet for real crypto.
1. **Use a separate `.env` (e.g. copy to `.env.testnet`) or override these in your current `.env`:**
- **TRON (Shasta testnet):**
`TRON_NODE_URL=https://api.shasta.trongrid.io`
Optionally set `USDT_TRC20_CONTRACT` to a Shasta test USDT token address if you use one (otherwise you can test TRX only).
- **Polygon (Amoy testnet):**
`POLYGON_RPC_URL=https://rpc-amoy.polygon.technology`
`USDC_POLYGON_CONTRACT=0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582`
(Official Circle USDC on Polygon Amoy; see [Circle USDC contract addresses](https://developers.circle.com/stablecoins/usdc-contract-addresses).)
2. **Get test tokens from faucets:**
- **TRON Shasta (test TRX):** e.g. [shasta.tronex.io](https://shasta.tronex.io/) or [faucet.triangleplatform.com/tron/shasta](https://faucet.triangleplatform.com/tron/shasta). Send your app’s TRON deposit address (from the Deposit screen) to receive test TRX.
- **Polygon Amoy (test USDC):** e.g. [faucet.circle.com](https://faucet.circle.com) (Circle) or other Amoy faucets. Use your app’s Polygon deposit address.
3. **Run the backend** with the testnet env; use the app to deposit (send test tokens to the shown address) and wait for the deposit monitor to credit the ledger. Then test withdrawals.
4. **When ready for production:** switch `.env` back to mainnet values (`TRON_NODE_URL=https://api.trongrid.io`, `POLYGON_RPC_URL=https://polygon-rpc.com`, `USDC_POLYGON_CONTRACT=0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359`, and remove or leave `USDT_TRC20_CONTRACT` unset). Use a **new** `PLATFORM_MNEMONIC` for production (do not reuse testnet mnemonic with real funds).
#### How to test deposit (exchange/wallet → platform)
1. **Get your platform deposit address**
- In the app: log in → **Deposit** → choose asset (e.g. TRX or USDC).
- Copy the address (and optionally use the QR code).
2. **Send funds to that address**
- **From an exchange:** In the exchange’s withdraw flow, choose the same network (e.g. TRON or Polygon), paste your **platform deposit address**, enter amount, confirm. (Use testnet on the exchange if it supports it; otherwise use mainnet with a small amount.)
- **From a wallet (e.g. TronLink, MetaMask):** Send the same asset on the same network to the **platform deposit address**.
- **Testnet only:** Use a faucet (see above) and enter your **platform deposit address** as the recipient; the faucet sends test tokens to your platform.
3. **Wait for the platform to credit the balance**
- The backend runs a **deposit monitor** every **60 seconds** (first run ~10 s after startup). It scans the chain for incoming transfers to your deposit address and credits your in-app balance once the required confirmations are met (e.g. 20 for TRON, 64 for Polygon).
- Refresh or reopen the dashboard; your balance should update after the next monitor run.
4. **Check the transaction**
- **Transactions** in the app should show the deposit with status **completed**.
#### How to test withdrawal (platform → exchange/wallet)
1. **Have balance and a hot wallet**
- Your in-app balance must be > 0 (from a prior deposit or a manual ledger credit for testing).
- Withdrawals are paid from a **hot wallet**. Ensure one is configured per asset (see [Hot wallet](#hot-wallet)).
2. **Get the destination address**
- **Exchange:** In the exchange, use “Deposit” for the same asset/network and copy the **deposit address** (and optional memo/tag if required).
- **Your own wallet:** Use the receiving address from TronLink, MetaMask, etc., on the same network.
3. **Withdraw in the app**
- In the app: **Withdraw** → choose asset → paste **destination address** → enter amount → enter **2FA code** → submit.
- The backend locks balance, sends from the hot wallet to that address, then marks the withdrawal completed.
4. **Confirm on chain**
- Check the destination wallet or exchange deposit history; the funds should appear after network confirmations. You can also look up the transaction ID (if shown in the app or logs) on a block explorer (e.g. Tronscan, Polygonscan).
In production, “exchange” is the same idea: **deposit** = user withdraws from exchange to the app’s deposit address; **withdraw** = user enters the exchange’s deposit address and the app sends from the platform to the exchange.
### Hot wallet
To enable withdrawals, insert a hot wallet per asset (e.g. via script or admin):
- Derive key from `PLATFORM_MNEMONIC` at a dedicated index (e.g. 0 for hot).
- Encrypt private key with app encryption.
- Insert into `hot_wallets` (wallet_type_id, address, encrypted_private_key).
---
## Docker deployment (VPS)
**Guide complet (français) :** [docs/DEPLOY-VPS.md](docs/DEPLOY-VPS.md) — **section 4** : démarrage sur base vierge (VPS et local).
Résumé — depuis la racine du dépôt :
```bash
cp .env.example .env
# Éditer .env (secrets, PostgreSQL, domaine, SMTP, INITIAL_SETUP_TOKEN)
# HTTPS (Let's Encrypt DNS, ports 9080/9443) :
npm run ssl:dns-init # une fois — validation TXT DNS
npm run phase-b:up:https # build + démarrage
# Premier admin : https://prediqo.redirectme.net:9443/setup
```
Commandes : `npm run phase-b:status` · `phase-b:logs` · `phase-b:restart` · `phase-b:down`
### Docker local (base vierge)
```bash
cp .env.docker.example .env.docker
# Éditer secrets + INITIAL_SETUP_TOKEN ; créer la base PostgreSQL locale
npm run docker:local:init
# Setup : http://localhost:9080/setup
```
### Run with Docker Compose (legacy / local)
```bash
cd backend
docker build -t crypto-wallet-api .
```
### Local migrate when using Docker Postgres
If Postgres is running in Docker and you run migrations from the host:
```bash
cd backend
# In .env use: DATABASE_URL=postgresql://cryptouser:cryptopass@localhost:5432/crypto_wallet
npm run migrate
```
---
## Tloto Mobile (Flutter)
### Setup
```bash
cd prediqo_mobile
flutter pub get
```
Configure API base URL:
- Default: `http://10.0.2.2:4000` (Android emulator).
- For iOS simulator: `http://127.0.0.1:4000`.
- Run with: `flutter run --dart-define=API_BASE_URL=http://YOUR_IP:4000`
### Structure
- **core**: API client (Dio + auth interceptor), secure storage, theme
- **data**: Models, repository implementations
- **features**: auth (login, register, 2FA), wallet (dashboard, deposit, withdraw)
- **BLoC**: AuthBloc, WalletBloc
### Screens
- Login / Register
- Dashboard (balances, recent transactions, deposit/withdraw entry)
- Deposit (QR + copy address per asset)
- Withdraw (asset, address, amount, 2FA code)
- 2FA setup (QR for TOTP)
---
## Tloto Web (React)
### Setup
```bash
cd prediqo_web
npm install
npm run dev
```
Configure API: copy `prediqo_web/.env.example` → `.env` with `VITE_API_BASE_URL=http://localhost:4000`.
**Modules (current & planned):**
- **Platform** — user management, settings, overview (implemented)
- **Player** — wallet + prediction games UI (to mirror mobile)
---
## Deposit flow
1. User opens Deposit for an asset; app shows unique address (and QR).
2. User sends crypto to that address from an exchange or external wallet.
3. Backend deposit monitor polls blockchain; after required confirmations, ledger is credited and a transaction record is created.
## Withdrawal flow
1. User enters amount, destination address, and 2FA code.
2. Backend checks balance, locks amount, signs from hot wallet, broadcasts tx.
3. Ledger is updated after processing; user sees status in app.
---
## Security
- Passwords hashed with Argon2.
- Private keys encrypted with AES-256 (key from env).
- 2FA (TOTP) for withdrawals and sensitive actions.
- Rate limiting on login and API.
- Audit log for login, deposits, withdrawals, admin actions.
---
## Future upgrades (from spec)
- MPC/HSM instead of single HD wallet
- Multi-sig or MPC for hot wallet
- Policy engine for withdrawal approvals
- Real-time monitoring and anomaly detection
- Double-entry accounting and fraud detection