-- Crypto Wallet Platform - PostgreSQL Schema -- Ledger is source of truth; blockchain confirms only. -- Roles CREATE TABLE IF NOT EXISTS roles ( id SERIAL PRIMARY KEY, name VARCHAR(50) UNIQUE NOT NULL, description TEXT ); INSERT INTO roles (name, description) VALUES ('user', 'Regular platform user'), ('moderator', 'Moderator with limited admin'), ('admin', 'Full platform administrator'), ('super_admin', 'Super administrator — approves sensitive fund operations') ON CONFLICT (name) DO NOTHING; -- Permissions (fine-grained capabilities assigned to roles) CREATE TABLE IF NOT EXISTS permissions ( id SERIAL PRIMARY KEY, key VARCHAR(100) UNIQUE NOT NULL, description TEXT ); INSERT INTO permissions (key, description) VALUES ('fund_operation.request', 'Submit fund operations for super-admin approval'), ('fund_operation.approve', 'Approve or reject pending fund operations'), ('user.manage_roles', 'Assign roles to users'), ('treasury.view', 'View treasury and funding data'), ('security.admin', 'Access security admin console'), ('ledger.credit', 'Request ledger credits (bonus / adjustments)'), ('referral.admin', 'Manage referral program admin actions'), ('settings.admin', 'Manage platform settings'), ('users.admin', 'Manage user accounts'), ('games.admin', 'Manage games catalog'), ('reports.admin', 'View admin reports and analytics') ON CONFLICT (key) DO NOTHING; CREATE TABLE IF NOT EXISTS role_permissions ( role_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE, permission_id INTEGER NOT NULL REFERENCES permissions(id) ON DELETE CASCADE, PRIMARY KEY (role_id, permission_id) ); -- user: no admin permissions -- moderator: support-related (inherits via staff checks in code) INSERT INTO role_permissions (role_id, permission_id) SELECT r.id, p.id FROM roles r CROSS JOIN permissions p WHERE r.name = 'moderator' AND p.key IN ('security.admin') ON CONFLICT DO NOTHING; INSERT INTO role_permissions (role_id, permission_id) SELECT r.id, p.id FROM roles r CROSS JOIN permissions p WHERE r.name = 'admin' AND p.key IN ( 'fund_operation.request', 'user.manage_roles', 'treasury.view', 'security.admin', 'ledger.credit', 'referral.admin', 'settings.admin', 'users.admin', 'games.admin', 'reports.admin' ) ON CONFLICT DO NOTHING; INSERT INTO role_permissions (role_id, permission_id) SELECT r.id, p.id FROM roles r CROSS JOIN permissions p WHERE r.name = 'super_admin' ON CONFLICT DO NOTHING; -- Users (sensitive fields encrypted at application layer) — must exist before user_roles / fund ops CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), first_name VARCHAR(100), middle_name VARCHAR(100), last_name VARCHAR(100), date_of_birth DATE, email_encrypted VARCHAR(255), email_hash VARCHAR(64) UNIQUE NOT NULL, phone_encrypted VARCHAR(255), phone_hash VARCHAR(64), password_hash VARCHAR(255) NOT NULL, role_id INTEGER NOT NULL REFERENCES roles(id) DEFAULT 1, email_verified BOOLEAN DEFAULT FALSE, phone_verified BOOLEAN DEFAULT FALSE, totp_secret_encrypted VARCHAR(512), totp_enabled BOOLEAN DEFAULT FALSE, is_enabled BOOLEAN NOT NULL DEFAULT TRUE, is_account_non_expired BOOLEAN NOT NULL DEFAULT TRUE, is_account_non_locked BOOLEAN NOT NULL DEFAULT TRUE, is_credentials_non_expired BOOLEAN NOT NULL DEFAULT TRUE, withdrawals_suspended BOOLEAN NOT NULL DEFAULT FALSE, under_surveillance BOOLEAN NOT NULL DEFAULT FALSE, security_suspended_at TIMESTAMPTZ, security_reason_encrypted TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_users_email_hash ON users(email_hash); CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone_hash_unique ON users(phone_hash) WHERE phone_hash IS NOT NULL; -- Many-to-many user ↔ roles CREATE TABLE IF NOT EXISTS user_roles ( user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, role_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE, created_at TIMESTAMPTZ DEFAULT NOW(), PRIMARY KEY (user_id, role_id) ); CREATE INDEX IF NOT EXISTS idx_user_roles_role ON user_roles(role_id); -- Per-user permission exceptions (allow / deny) layered on top of role grants CREATE TABLE IF NOT EXISTS user_permission_overrides ( user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, permission_id INTEGER NOT NULL REFERENCES permissions(id) ON DELETE CASCADE, effect VARCHAR(8) NOT NULL CHECK (effect IN ('allow', 'deny')), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), updated_by UUID REFERENCES users(id), PRIMARY KEY (user_id, permission_id) ); CREATE INDEX IF NOT EXISTS idx_user_permission_overrides_permission ON user_permission_overrides(permission_id); CREATE INDEX IF NOT EXISTS idx_user_permission_overrides_effect ON user_permission_overrides(effect); -- Backfill user_roles from legacy users.role_id INSERT INTO user_roles (user_id, role_id) SELECT u.id, u.role_id FROM users u ON CONFLICT DO NOTHING; -- Fund operation approval queue CREATE TABLE IF NOT EXISTS fund_operation_requests ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), operation_type VARCHAR(64) NOT NULL CHECK (operation_type IN ( 'ledger_credit', 'treasury_cold_to_hot', 'treasury_hot_to_cold', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas', 'user_withdrawal', 'approval_policy_change' )), status VARCHAR(32) NOT NULL DEFAULT 'pending_approval' CHECK (status IN ( 'pending_approval', 'approved', 'processing', 'confirmed', 'executed', 'failed', 'rejected', 'cancelled' )), payload JSONB NOT NULL DEFAULT '{}', requested_by UUID NOT NULL REFERENCES users(id), approved_by UUID REFERENCES users(id), rejection_reason TEXT, execution_result JSONB, policy_id UUID, policy_snapshot JSONB, required_quorum JSONB, amount_raw TEXT, asset_code VARCHAR(64), network VARCHAR(32), from_address VARCHAR(255), to_address VARCHAR(255), created_at TIMESTAMPTZ DEFAULT NOW(), approved_at TIMESTAMPTZ, executed_at TIMESTAMPTZ ); CREATE INDEX IF NOT EXISTS idx_fund_operation_requests_status ON fund_operation_requests(status); CREATE INDEX IF NOT EXISTS idx_fund_operation_requests_type ON fund_operation_requests(operation_type); CREATE INDEX IF NOT EXISTS idx_fund_operation_requests_requested ON fund_operation_requests(requested_by); ALTER TABLE fund_operation_requests DROP CONSTRAINT IF EXISTS fund_operation_requests_operation_type_check; ALTER TABLE fund_operation_requests ADD CONSTRAINT fund_operation_requests_operation_type_check CHECK (operation_type IN ( 'ledger_credit', 'treasury_cold_to_hot', 'treasury_hot_to_cold', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas', 'user_withdrawal', 'approval_policy_change' )); ALTER TABLE fund_operation_requests DROP CONSTRAINT IF EXISTS fund_operation_requests_status_check; ALTER TABLE fund_operation_requests ADD CONSTRAINT fund_operation_requests_status_check CHECK (status IN ( 'pending_approval', 'approved', 'processing', 'confirmed', 'executed', 'failed', 'rejected', 'cancelled' )); ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS policy_id UUID; ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS policy_snapshot JSONB; ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS required_quorum JSONB; ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS amount_raw TEXT; ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS asset_code VARCHAR(64); ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS network VARCHAR(32); ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS from_address VARCHAR(255); ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS to_address VARCHAR(255); -- Configurable approval policies (N-of-M) CREATE TABLE IF NOT EXISTS approval_policies ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(128) NOT NULL, enabled BOOLEAN NOT NULL DEFAULT true, priority INTEGER NOT NULL DEFAULT 100, operation_type VARCHAR(64), wallet_type_id INTEGER REFERENCES wallet_types(id), network VARCHAR(32), amount_min_raw TEXT, amount_max_raw TEXT, source_wallet_kind VARCHAR(16) NOT NULL DEFAULT 'any' CHECK (source_wallet_kind IN ('hot', 'cold', 'hd', 'user', 'any')), dest_wallet_kind VARCHAR(16) NOT NULL DEFAULT 'any' CHECK (dest_wallet_kind IN ('hot', 'cold', 'hd', 'user', 'any')), decision JSONB NOT NULL DEFAULT '{}', version INTEGER NOT NULL DEFAULT 1, updated_by UUID REFERENCES users(id), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_approval_policies_enabled_priority ON approval_policies(enabled, priority); CREATE TABLE IF NOT EXISTS approval_policy_revisions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), change_request_id UUID REFERENCES fund_operation_requests(id), actor_id UUID REFERENCES users(id), before_snapshot JSONB NOT NULL DEFAULT '[]', after_snapshot JSONB NOT NULL DEFAULT '[]', note TEXT, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_approval_policy_revisions_created ON approval_policy_revisions(created_at DESC); CREATE TABLE IF NOT EXISTS fund_operation_votes ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), request_id UUID NOT NULL REFERENCES fund_operation_requests(id) ON DELETE CASCADE, voter_id UUID NOT NULL REFERENCES users(id), decision VARCHAR(16) NOT NULL CHECK (decision IN ('approve', 'reject')), reason TEXT, voter_roles JSONB NOT NULL DEFAULT '[]', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE (request_id, voter_id) ); CREATE INDEX IF NOT EXISTS idx_fund_operation_votes_request ON fund_operation_votes(request_id); -- Batched automatic deposit sweeps awaiting approval CREATE TABLE IF NOT EXISTS deposit_sweep_batches ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), status VARCHAR(32) NOT NULL DEFAULT 'pending_batch' CHECK (status IN ( 'pending_batch', 'pending_approval', 'approved', 'executing', 'completed', 'failed', 'cancelled' )), sweep_count INTEGER NOT NULL DEFAULT 0, fund_request_id UUID REFERENCES fund_operation_requests(id), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_deposit_sweep_batches_status ON deposit_sweep_batches(status); -- Refresh tokens CREATE TABLE IF NOT EXISTS refresh_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_hash VARCHAR(255) NOT NULL, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens(user_id); CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires ON refresh_tokens(expires_at); -- Wallet types (USDT on TRON TRC20 + BSC BEP20) CREATE TABLE IF NOT EXISTS wallet_types ( id SERIAL PRIMARY KEY, code VARCHAR(32) UNIQUE NOT NULL, name VARCHAR(100) NOT NULL, network VARCHAR(50) NOT NULL, decimals INTEGER NOT NULL DEFAULT 6, contract_address VARCHAR(255) ); INSERT INTO wallet_types (code, name, network, decimals, contract_address) VALUES ('USDT_TRC20', 'USDT (TRC20)', 'TRON', 6, 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'), ('USDT_BEP20', 'USDT (BEP20)', 'BSC', 18, '0x55d398326f99059fF775485246999027B3197955') ON CONFLICT (code) DO NOTHING; -- User deposit addresses (derived from HD wallet; only public address stored) CREATE TABLE IF NOT EXISTS user_wallets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), address VARCHAR(255) NOT NULL, derivation_index INTEGER NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(user_id, wallet_type_id) ); CREATE INDEX IF NOT EXISTS idx_user_wallets_user ON user_wallets(user_id); CREATE INDEX IF NOT EXISTS idx_user_wallets_address ON user_wallets(address); CREATE INDEX IF NOT EXISTS idx_user_wallets_type ON user_wallets(wallet_type_id); -- On-chain USDT still sitting on user HD deposit addresses (ops visibility). CREATE TABLE IF NOT EXISTS deposit_hd_snapshots ( user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), address VARCHAR(255) NOT NULL, on_chain_amount NUMERIC(78, 0) NOT NULL DEFAULT 0, last_checked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (user_id, wallet_type_id) ); CREATE INDEX IF NOT EXISTS idx_deposit_hd_snapshots_amount ON deposit_hd_snapshots(on_chain_amount) WHERE on_chain_amount > 0; -- Per-network deposit inventory (ops telemetry; micro-USDT 6 decimals). Not a withdrawal cap. CREATE TABLE IF NOT EXISTS user_network_inventory ( user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, network VARCHAR(16) NOT NULL CHECK (network IN ('TRON', 'BSC')), amount BIGINT NOT NULL DEFAULT 0 CHECK (amount >= 0), updated_at TIMESTAMPTZ DEFAULT NOW(), PRIMARY KEY (user_id, network) ); CREATE INDEX IF NOT EXISTS idx_user_network_inventory_user ON user_network_inventory(user_id); -- Hot wallet addresses (platform signs withdrawals from these) CREATE TABLE IF NOT EXISTS hot_wallets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), address VARCHAR(255) NOT NULL, encrypted_private_key TEXT NOT NULL, derivation_index INTEGER, is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_hot_wallets_type ON hot_wallets(wallet_type_id); -- Ledger: canonical source of truth for balances CREATE TABLE IF NOT EXISTS ledger_accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), available_balance BIGINT NOT NULL DEFAULT 0, locked_balance BIGINT NOT NULL DEFAULT 0, account_kind VARCHAR(16) NOT NULL DEFAULT 'main' CHECK (account_kind IN ('main', 'bonus', 'test')), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_accounts_user_wallet_kind ON ledger_accounts(user_id, wallet_type_id, account_kind); CREATE INDEX IF NOT EXISTS idx_ledger_user ON ledger_accounts(user_id); CREATE INDEX IF NOT EXISTS idx_ledger_wallet_type ON ledger_accounts(wallet_type_id); -- Ledger entries (double-entry style for audit) CREATE TABLE IF NOT EXISTS ledger_entries ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), account_id UUID NOT NULL REFERENCES ledger_accounts(id), type VARCHAR(32) NOT NULL, amount BIGINT NOT NULL, balance_after BIGINT NOT NULL, reference_type VARCHAR(50), reference_id UUID, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_ledger_entries_account ON ledger_entries(account_id); CREATE INDEX IF NOT EXISTS idx_ledger_entries_created ON ledger_entries(created_at); CREATE INDEX IF NOT EXISTS idx_ledger_entries_reference ON ledger_entries(reference_type, reference_id); -- Transactions (deposits, withdrawals, transfers) CREATE TABLE IF NOT EXISTS transactions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id), wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), type VARCHAR(32) NOT NULL, amount BIGINT NOT NULL, fee BIGINT DEFAULT 0, status VARCHAR(32) NOT NULL DEFAULT 'pending', blockchain_tx_id VARCHAR(255), from_address VARCHAR(255), to_address VARCHAR(255), confirmations INTEGER DEFAULT 0, required_confirmations INTEGER, metadata JSONB, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_transactions_user ON transactions(user_id); CREATE INDEX IF NOT EXISTS idx_transactions_status ON transactions(status); CREATE INDEX IF NOT EXISTS idx_transactions_blockchain_tx ON transactions(blockchain_tx_id); CREATE UNIQUE INDEX IF NOT EXISTS idx_transactions_blockchain_tx_unique ON transactions (blockchain_tx_id) WHERE blockchain_tx_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_transactions_created ON transactions(created_at); CREATE INDEX IF NOT EXISTS idx_transactions_type ON transactions(type); -- Withdrawal locks (amount locked while withdrawal is processing) CREATE TABLE IF NOT EXISTS withdrawal_locks ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id), wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), transaction_id UUID REFERENCES transactions(id), amount BIGINT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), expires_at TIMESTAMPTZ ); CREATE INDEX IF NOT EXISTS idx_withdrawal_locks_user ON withdrawal_locks(user_id); -- Deposit monitoring: track scanned blocks to avoid re-processing CREATE TABLE IF NOT EXISTS deposit_scanner_state ( id SERIAL PRIMARY KEY, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), last_block BIGINT NOT NULL DEFAULT 0, updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(wallet_type_id) ); -- Audit log for sensitive actions CREATE TABLE IF NOT EXISTS audit_logs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES users(id), action VARCHAR(100) NOT NULL, resource_type VARCHAR(50), resource_id VARCHAR(255), ip_address VARCHAR(45), user_agent TEXT, metadata JSONB, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_audit_logs_user ON audit_logs(user_id); CREATE INDEX IF NOT EXISTS idx_audit_logs_action ON audit_logs(action); CREATE INDEX IF NOT EXISTS idx_audit_logs_created ON audit_logs(created_at); -- Exchange funding records (platform moves to/from exchange) CREATE TABLE IF NOT EXISTS exchange_funding ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), direction VARCHAR(20) NOT NULL, amount BIGINT NOT NULL, blockchain_tx_id VARCHAR(255), exchange_name VARCHAR(50), status VARCHAR(32) NOT NULL DEFAULT 'pending', approved_by UUID REFERENCES users(id), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_exchange_funding_status ON exchange_funding(status); ALTER TABLE exchange_funding ADD COLUMN IF NOT EXISTS requested_by UUID REFERENCES users(id); -- System settings (admin-configurable: password policy, token expiry) CREATE TABLE IF NOT EXISTS system_settings ( key VARCHAR(100) PRIMARY KEY, value TEXT NOT NULL, updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO system_settings (key, value) VALUES ('password_min_length', '8'), ('password_require_uppercase', 'true'), ('password_require_lowercase', 'true'), ('password_require_number', 'true'), ('password_require_special', 'true'), ('access_token_expiry', '15m'), ('refresh_token_expiry', '7d') ON CONFLICT (key) DO NOTHING; -- Migration: add account status columns to users (for existing DBs) DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_enabled') THEN ALTER TABLE users ADD COLUMN is_enabled BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_account_non_expired') THEN ALTER TABLE users ADD COLUMN is_account_non_expired BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_account_non_locked') THEN ALTER TABLE users ADD COLUMN is_account_non_locked BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_credentials_non_expired') THEN ALTER TABLE users ADD COLUMN is_credentials_non_expired BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'first_name') THEN ALTER TABLE users ADD COLUMN first_name VARCHAR(100); END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'middle_name') THEN ALTER TABLE users ADD COLUMN middle_name VARCHAR(100); END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'last_name') THEN ALTER TABLE users ADD COLUMN last_name VARCHAR(100); END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'date_of_birth') THEN ALTER TABLE users ADD COLUMN date_of_birth DATE; END IF; END $$; -- Email verification tokens (single-use, hashed at rest) CREATE TABLE IF NOT EXISTS email_verification_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_hash VARCHAR(64) NOT NULL, expires_at TIMESTAMPTZ NOT NULL, used_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_user ON email_verification_tokens(user_id); CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_hash ON email_verification_tokens(token_hash); CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_expires ON email_verification_tokens(expires_at); -- Password reset tokens (single-use, hashed at rest) CREATE TABLE IF NOT EXISTS password_reset_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_hash VARCHAR(64) NOT NULL, expires_at TIMESTAMPTZ NOT NULL, used_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user ON password_reset_tokens(user_id); CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_hash ON password_reset_tokens(token_hash); CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_expires ON password_reset_tokens(expires_at); -- Countries catalog (synced from REST Countries API; admin can block registration) CREATE TABLE IF NOT EXISTS countries ( code CHAR(2) PRIMARY KEY, name VARCHAR(120) NOT NULL, registration_allowed BOOLEAN NOT NULL DEFAULT TRUE, synced_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_countries_registration ON countries(registration_allowed); INSERT INTO system_settings (key, value) VALUES ('require_email_verification_for_login', 'true') ON CONFLICT (key) DO NOTHING; -- Runtime ops defaults (env-backed until admin overrides via Settings UI) INSERT INTO system_settings (key, value) VALUES ('allow_withdrawals', 'false'), ('network_usdt_trc20_deposit_enabled', 'true'), ('network_usdt_trc20_withdraw_enabled', 'true'), ('network_usdt_bep20_deposit_enabled', 'true'), ('network_usdt_bep20_withdraw_enabled', 'true'), ('rate_limit_window_ms', '900000'), ('rate_limit_max', '2000'), ('login_rate_limit_max', '20'), ('daily_withdrawal_limit_usd', '10000'), ('large_withdrawal_threshold_usd', '1000'), ('candle_predict_engine_tick_ms', '3000'), ('candle_predict_backfill_max_per_tick', '2'), ('candle_predict_backfill_interval_ms', '60000'), ('candle_predict_backfill_seed_max', '15') ON CONFLICT (key) DO NOTHING; INSERT INTO system_settings (key, value) VALUES ('withdrawal_network_fee_usdt_micro', '2000000') ON CONFLICT (key) DO NOTHING; INSERT INTO system_settings (key, value) VALUES ('transfer_min_remaining_usdt_micro', '0') ON CONFLICT (key) DO NOTHING; -- Games catalog (prediction games available on the platform) CREATE TABLE IF NOT EXISTS games ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), slug VARCHAR(80) UNIQUE NOT NULL, title VARCHAR(150) NOT NULL, description TEXT, category VARCHAR(50) NOT NULL DEFAULT 'prediction', thumbnail_url TEXT, accent_color VARCHAR(16) DEFAULT '#D6B25E', status VARCHAR(32) NOT NULL DEFAULT 'active', sort_order INTEGER NOT NULL DEFAULT 0, is_featured BOOLEAN NOT NULL DEFAULT FALSE, implementation_key VARCHAR(64), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Existing databases: add implementation_key before indexes/inserts that reference it DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'games' AND column_name = 'implementation_key' ) THEN ALTER TABLE games ADD COLUMN implementation_key VARCHAR(64); END IF; END $$; UPDATE games SET implementation_key = 'candle-predict' WHERE slug = 'candle-predict' AND implementation_key IS NULL; CREATE INDEX IF NOT EXISTS idx_games_status ON games(status); CREATE INDEX IF NOT EXISTS idx_games_sort ON games(sort_order); CREATE INDEX IF NOT EXISTS idx_games_featured ON games(is_featured); CREATE INDEX IF NOT EXISTS idx_games_implementation ON games(implementation_key) WHERE implementation_key IS NOT NULL; -- Dynamic advertisements / promotions (home page and placements) CREATE TABLE IF NOT EXISTS advertisements ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), placement VARCHAR(50) NOT NULL DEFAULT 'home_hero', title VARCHAR(200) NOT NULL, subtitle TEXT, cta_label VARCHAR(80), link_url TEXT, image_url TEXT, background_gradient TEXT, accent_color VARCHAR(16) DEFAULT '#7C5CFF', is_active BOOLEAN NOT NULL DEFAULT TRUE, sort_order INTEGER NOT NULL DEFAULT 0, starts_at TIMESTAMPTZ, ends_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_advertisements_placement ON advertisements(placement); CREATE INDEX IF NOT EXISTS idx_advertisements_active ON advertisements(is_active); CREATE INDEX IF NOT EXISTS idx_advertisements_sort ON advertisements(sort_order); INSERT INTO games (slug, title, description, category, accent_color, status, sort_order, is_featured, implementation_key) VALUES ('candle-predict', 'Candle Predict', 'Predict Short (bearish) or Long (bullish) on the next synthetic candle. The minority stake pool wins when pools differ enough.', 'prediction', '#D6B25E', 'active', 1, TRUE, 'candle-predict') ON CONFLICT (slug) DO NOTHING; -- Remove placeholder games from existing databases (keep only Candle Predict) DELETE FROM games WHERE slug <> 'candle-predict'; -- Candle Predict game configuration (single row) CREATE TABLE IF NOT EXISTS candle_predict_config ( id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), interval_minutes INTEGER NOT NULL DEFAULT 1, stake_amounts JSONB NOT NULL DEFAULT '[1,5,10,20,50,100,1000]'::jsonb, min_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 0.01, max_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 1000, pool_winner_rule VARCHAR(16) NOT NULL DEFAULT 'minority', allowed_intervals JSONB NOT NULL DEFAULT '[1,3,5,10]'::jsonb, prediction_window_seconds INTEGER NOT NULL DEFAULT 15, tie_tolerance_percent NUMERIC(5,2) NOT NULL DEFAULT 2.00, tie_tolerance_max_percent NUMERIC(5,2) NOT NULL DEFAULT 95.00, tie_tolerance_min_enabled BOOLEAN NOT NULL DEFAULT TRUE, tie_tolerance_max_enabled BOOLEAN NOT NULL DEFAULT TRUE, base_price NUMERIC(18,6) NOT NULL DEFAULT 100.000000, payout_multiplier NUMERIC(6,3) NOT NULL DEFAULT 1.900, pool_multiplier NUMERIC(6,3) NOT NULL DEFAULT 1.900, daily_revenue_target NUMERIC(18,6) NOT NULL DEFAULT 0, daily_revenue_overflow_strategy VARCHAR(16) NOT NULL DEFAULT 'neutral', wallet_type_code VARCHAR(32) NOT NULL DEFAULT 'USDT_TRC20', auto_modes JSONB NOT NULL DEFAULT '["each_round","interval"]'::jsonb, is_active BOOLEAN NOT NULL DEFAULT TRUE, -- Display-only synthetic instrument branding (OHLC still from Tloto engine). instrument_symbol VARCHAR(16) NOT NULL DEFAULT 'FO', instrument_display_name VARCHAR(64) NOT NULL DEFAULT 'Full Option', instrument_quote_currency VARCHAR(16) NOT NULL DEFAULT 'USDT', instrument_price_digits SMALLINT NOT NULL DEFAULT 2 CHECK (instrument_price_digits >= 0 AND instrument_price_digits <= 8), updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO candle_predict_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING; CREATE TABLE IF NOT EXISTS candle_predict_rounds ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), candle_open_ms BIGINT NOT NULL, interval_minutes INTEGER NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'betting', short_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0, long_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0, open_price NUMERIC(24,8), high_price NUMERIC(24,8), low_price NUMERIC(24,8), close_price NUMERIC(24,8), outcome VARCHAR(20), neutral_color VARCHAR(10), total_bets INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMPTZ DEFAULT NOW(), settled_at TIMESTAMPTZ ); CREATE INDEX IF NOT EXISTS idx_candle_rounds_status ON candle_predict_rounds(status); CREATE INDEX IF NOT EXISTS idx_candle_rounds_open ON candle_predict_rounds(candle_open_ms); CREATE TABLE IF NOT EXISTS candle_predict_bets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), round_id UUID NOT NULL REFERENCES candle_predict_rounds(id) ON DELETE CASCADE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, direction VARCHAR(10) NOT NULL CHECK (direction IN ('short', 'long')), stake_raw BIGINT NOT NULL, stake_display NUMERIC(18,6) NOT NULL, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), status VARCHAR(20) NOT NULL DEFAULT 'pending', interval_minutes INTEGER NOT NULL DEFAULT 1, payout_raw BIGINT NOT NULL DEFAULT 0, is_auto BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE (round_id, user_id) ); CREATE INDEX IF NOT EXISTS idx_candle_bets_user ON candle_predict_bets(user_id); CREATE INDEX IF NOT EXISTS idx_candle_bets_round ON candle_predict_bets(round_id); CREATE TABLE IF NOT EXISTS candle_predict_candles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), candle_open_ms BIGINT NOT NULL, interval_minutes INTEGER NOT NULL DEFAULT 1, open_price NUMERIC(24,8) NOT NULL, high_price NUMERIC(24,8) NOT NULL, low_price NUMERIC(24,8) NOT NULL, close_price NUMERIC(24,8) NOT NULL, color_hint VARCHAR(10) NOT NULL DEFAULT 'green', outcome VARCHAR(20) NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_candle_predict_candles_open ON candle_predict_candles(candle_open_ms); DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'tie_tolerance_percent') THEN ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_percent NUMERIC(5,2) NOT NULL DEFAULT 2.00; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'base_price') THEN ALTER TABLE candle_predict_config ADD COLUMN base_price NUMERIC(18,6) NOT NULL DEFAULT 100.000000; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'min_stake_amount') THEN ALTER TABLE candle_predict_config ADD COLUMN min_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 0.01; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'max_stake_amount') THEN ALTER TABLE candle_predict_config ADD COLUMN max_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 1000; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'pool_winner_rule') THEN ALTER TABLE candle_predict_config ADD COLUMN pool_winner_rule VARCHAR(16) NOT NULL DEFAULT 'minority'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'short_pool_display') THEN ALTER TABLE candle_predict_rounds ADD COLUMN short_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'long_pool_display') THEN ALTER TABLE candle_predict_rounds ADD COLUMN long_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'outcome') THEN ALTER TABLE candle_predict_rounds ADD COLUMN outcome VARCHAR(20); END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'neutral_color') THEN ALTER TABLE candle_predict_rounds ADD COLUMN neutral_color VARCHAR(10); END IF; -- Legacy columns from Binance-based version (removed in synthetic engine) IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_rounds' AND column_name = 'symbol') THEN ALTER TABLE candle_predict_rounds DROP COLUMN symbol; END IF; IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_rounds' AND column_name = 'result') THEN ALTER TABLE candle_predict_rounds DROP COLUMN result; END IF; IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'symbol') THEN ALTER TABLE candle_predict_config DROP COLUMN symbol; END IF; IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'long_body_min_ratio') THEN ALTER TABLE candle_predict_config DROP COLUMN long_body_min_ratio; END IF; UPDATE games SET description = 'Predict Short (bearish) or Long (bullish) on the next synthetic candle. The minority stake pool wins when pools differ enough.' WHERE slug = 'candle-predict'; -- Legacy Binance defaults (5m / 15s window) made betting nearly invisible; move to playable defaults once. UPDATE candle_predict_config SET interval_minutes = 1, prediction_window_seconds = 45 WHERE id = 1 AND interval_minutes = 5 AND prediction_window_seconds = 15; UPDATE candle_predict_config SET prediction_window_seconds = 45 WHERE id = 1 AND interval_minutes = 1 AND prediction_window_seconds >= 60; END $$; -- Multi-interval Candle Predict (configurable periods, separate rounds/candles per interval) CREATE TABLE IF NOT EXISTS candle_predict_intervals ( id SERIAL PRIMARY KEY, interval_minutes INTEGER NOT NULL UNIQUE, label VARCHAR(64) NOT NULL, sort_order INTEGER NOT NULL DEFAULT 0, is_active BOOLEAN NOT NULL DEFAULT TRUE, is_default BOOLEAN NOT NULL DEFAULT FALSE, prediction_window_seconds INTEGER, tie_tolerance_percent NUMERIC(5,2), tie_tolerance_max_percent NUMERIC(5,2), tie_tolerance_min_enabled BOOLEAN, tie_tolerance_max_enabled BOOLEAN, payout_multiplier NUMERIC(6,3), pool_multiplier NUMERIC(6,3), base_price NUMERIC(18,6), chart_candle_limit INTEGER NOT NULL DEFAULT 120, updated_at TIMESTAMPTZ DEFAULT NOW() ); DO $$ DECLARE mins INTEGER; ord INTEGER := 0; BEGIN IF NOT EXISTS (SELECT 1 FROM candle_predict_intervals LIMIT 1) THEN FOR mins IN SELECT unnest(ARRAY[1, 3, 5, 10, 15]) AS m LOOP ord := ord + 1; INSERT INTO candle_predict_intervals (interval_minutes, label, sort_order, is_default, is_active) VALUES (mins, mins || ' min', ord, mins = 1, TRUE) ON CONFLICT (interval_minutes) DO NOTHING; END LOOP; END IF; IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_candles' AND column_name = 'interval_minutes' ) = FALSE THEN ALTER TABLE candle_predict_candles ADD COLUMN interval_minutes INTEGER NOT NULL DEFAULT 1; END IF; IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_bets' AND column_name = 'interval_minutes' ) = FALSE THEN ALTER TABLE candle_predict_bets ADD COLUMN interval_minutes INTEGER NOT NULL DEFAULT 1; END IF; IF EXISTS ( SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'candle_predict_rounds' AND constraint_name = 'candle_predict_rounds_candle_open_ms_key' ) THEN ALTER TABLE candle_predict_rounds DROP CONSTRAINT candle_predict_rounds_candle_open_ms_key; END IF; IF NOT EXISTS ( SELECT 1 FROM pg_indexes WHERE indexname = 'uq_candle_rounds_open_interval' ) THEN CREATE UNIQUE INDEX uq_candle_rounds_open_interval ON candle_predict_rounds(candle_open_ms, interval_minutes); END IF; IF EXISTS ( SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'candle_predict_candles' AND constraint_name = 'candle_predict_candles_candle_open_ms_key' ) THEN ALTER TABLE candle_predict_candles DROP CONSTRAINT candle_predict_candles_candle_open_ms_key; END IF; IF NOT EXISTS ( SELECT 1 FROM pg_indexes WHERE indexname = 'uq_candle_candles_open_interval' ) THEN CREATE UNIQUE INDEX uq_candle_candles_open_interval ON candle_predict_candles(candle_open_ms, interval_minutes); END IF; END $$; CREATE INDEX IF NOT EXISTS idx_candle_rounds_interval ON candle_predict_rounds(interval_minutes); CREATE INDEX IF NOT EXISTS idx_candle_candles_interval ON candle_predict_candles(interval_minutes); CREATE INDEX IF NOT EXISTS idx_candle_bets_interval ON candle_predict_bets(interval_minutes); CREATE TABLE IF NOT EXISTS candle_predict_auto_settings ( user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, enabled BOOLEAN NOT NULL DEFAULT FALSE, direction VARCHAR(10) CHECK (direction IN ('short', 'long')), stake_display NUMERIC(18,6) NOT NULL DEFAULT 1, mode VARCHAR(20) NOT NULL DEFAULT 'each_round' CHECK (mode IN ('each_round', 'interval')), interval_seconds INTEGER DEFAULT 60, period_minutes INTEGER NOT NULL DEFAULT 1, last_auto_bet_at TIMESTAMPTZ, updated_at TIMESTAMPTZ DEFAULT NOW() ); DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_auto_settings' AND column_name = 'period_minutes' ) THEN ALTER TABLE candle_predict_auto_settings ADD COLUMN period_minutes INTEGER NOT NULL DEFAULT 1; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_auto_settings' AND column_name = 'stake_account_kind' ) THEN ALTER TABLE candle_predict_auto_settings ADD COLUMN stake_account_kind VARCHAR(16) NOT NULL DEFAULT 'main' CHECK (stake_account_kind IN ('main', 'bonus')); END IF; END $$; -- Phase 1 security: user withdrawal controls & surveillance DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'withdrawals_suspended' ) THEN ALTER TABLE users ADD COLUMN withdrawals_suspended BOOLEAN NOT NULL DEFAULT FALSE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'under_surveillance' ) THEN ALTER TABLE users ADD COLUMN under_surveillance BOOLEAN NOT NULL DEFAULT FALSE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'security_suspended_at' ) THEN ALTER TABLE users ADD COLUMN security_suspended_at TIMESTAMPTZ; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'security_reason_encrypted' ) THEN ALTER TABLE users ADD COLUMN security_reason_encrypted TEXT; END IF; END $$; CREATE INDEX IF NOT EXISTS idx_users_withdrawals_suspended ON users(withdrawals_suspended) WHERE withdrawals_suspended = TRUE; CREATE INDEX IF NOT EXISTS idx_users_under_surveillance ON users(under_surveillance) WHERE under_surveillance = TRUE; CREATE TABLE IF NOT EXISTS security_alerts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES users(id) ON DELETE SET NULL, severity VARCHAR(20) NOT NULL DEFAULT 'high' CHECK (severity IN ('low', 'medium', 'high', 'critical')), alert_type VARCHAR(64) NOT NULL, status VARCHAR(32) NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'investigating', 'resolved', 'dismissed')), title VARCHAR(255) NOT NULL, details_encrypted TEXT, metadata JSONB, resolved_by UUID REFERENCES users(id), resolved_at TIMESTAMPTZ, resolution_note_encrypted TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_security_alerts_status ON security_alerts(status); CREATE INDEX IF NOT EXISTS idx_security_alerts_user ON security_alerts(user_id); CREATE INDEX IF NOT EXISTS idx_security_alerts_created ON security_alerts(created_at DESC); CREATE INDEX IF NOT EXISTS idx_security_alerts_type ON security_alerts(alert_type); -- Phase 2 treasury: cold storage (watch-only addresses) and deposit sweeps CREATE TABLE IF NOT EXISTS cold_wallets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), address VARCHAR(255) NOT NULL, label VARCHAR(100), is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_cold_wallets_type ON cold_wallets(wallet_type_id); CREATE UNIQUE INDEX IF NOT EXISTS idx_cold_wallets_active_type ON cold_wallets(wallet_type_id) WHERE is_active = TRUE; CREATE TABLE IF NOT EXISTS deposit_sweeps ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), from_address VARCHAR(255) NOT NULL, to_cold_address VARCHAR(255) NOT NULL, amount BIGINT NOT NULL, blockchain_tx_id VARCHAR(255), status VARCHAR(32) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'gas_funding', 'broadcasting', 'completed', 'failed', 'skipped')), deposit_transaction_id UUID REFERENCES transactions(id), error_message_encrypted TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE UNIQUE INDEX IF NOT EXISTS idx_deposit_sweeps_deposit_tx ON deposit_sweeps(deposit_transaction_id) WHERE deposit_transaction_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_deposit_sweeps_status ON deposit_sweeps(status); CREATE INDEX IF NOT EXISTS idx_deposit_sweeps_user ON deposit_sweeps(user_id); ALTER TABLE deposit_sweeps ADD COLUMN IF NOT EXISTS batch_id UUID REFERENCES deposit_sweep_batches(id); CREATE INDEX IF NOT EXISTS idx_deposit_sweeps_batch ON deposit_sweeps(batch_id); -- Phase 3: ledger integrity snapshots (detect direct DB balance tampering) CREATE TABLE IF NOT EXISTS ledger_integrity_snapshots ( account_id UUID PRIMARY KEY REFERENCES ledger_accounts(id) ON DELETE CASCADE, available_balance BIGINT NOT NULL, locked_balance BIGINT NOT NULL, entries_sum BIGINT NOT NULL, last_entry_at TIMESTAMPTZ, snapshot_at TIMESTAMPTZ DEFAULT NOW() ); -- Phase 4: in-app admin notifications CREATE TABLE IF NOT EXISTS admin_notifications ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), title VARCHAR(255) NOT NULL, body_encrypted TEXT, severity VARCHAR(20) NOT NULL DEFAULT 'info' CHECK (severity IN ('info', 'low', 'medium', 'high', 'critical')), alert_id UUID REFERENCES security_alerts(id) ON DELETE SET NULL, read_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_admin_notifications_unread ON admin_notifications(created_at DESC) WHERE read_at IS NULL; -- Phase 5: approved ledger credits (bonus / admin adjustment) CREATE TABLE IF NOT EXISTS ledger_adjustments ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), adjustment_type VARCHAR(32) NOT NULL CHECK (adjustment_type IN ('bonus', 'admin_adjustment')), amount BIGINT NOT NULL CHECK (amount > 0), reason_encrypted TEXT NOT NULL, approved_by UUID NOT NULL REFERENCES users(id), transaction_id UUID REFERENCES transactions(id), created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_user ON ledger_adjustments(user_id); CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_created ON ledger_adjustments(created_at DESC); ALTER TABLE ledger_adjustments ADD COLUMN IF NOT EXISTS requested_by UUID REFERENCES users(id); -- Referral program & bonus accounts DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'referral_code' ) THEN ALTER TABLE users ADD COLUMN referral_code VARCHAR(32); ALTER TABLE users ADD COLUMN referred_by_user_id UUID REFERENCES users(id); ALTER TABLE users ADD COLUMN country_of_residence VARCHAR(2); ALTER TABLE users ADD COLUMN nationality VARCHAR(2); ALTER TABLE users ADD COLUMN first_deposit_at TIMESTAMPTZ; ALTER TABLE users ADD COLUMN first_deposit_transaction_id UUID REFERENCES transactions(id); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ledger_accounts' AND column_name = 'account_kind' ) THEN ALTER TABLE ledger_accounts ADD COLUMN account_kind VARCHAR(16) NOT NULL DEFAULT 'main' CHECK (account_kind IN ('main', 'bonus')); ALTER TABLE ledger_accounts DROP CONSTRAINT IF EXISTS ledger_accounts_user_id_wallet_type_id_key; CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_accounts_user_wallet_kind ON ledger_accounts(user_id, wallet_type_id, account_kind); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_bets' AND column_name = 'stake_account_kind' ) THEN ALTER TABLE candle_predict_bets ADD COLUMN stake_account_kind VARCHAR(16) NOT NULL DEFAULT 'main' CHECK (stake_account_kind IN ('main', 'bonus')); END IF; END $$; CREATE UNIQUE INDEX IF NOT EXISTS idx_users_referral_code ON users(referral_code) WHERE referral_code IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_users_referred_by ON users(referred_by_user_id); CREATE INDEX IF NOT EXISTS idx_users_country ON users(country_of_residence); CREATE INDEX IF NOT EXISTS idx_users_nationality ON users(nationality); CREATE TABLE IF NOT EXISTS referral_program_settings ( id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT TRUE, default_referrer_user_id UUID REFERENCES users(id), bonus_withdrawable BOOLEAN NOT NULL DEFAULT FALSE, referrer_must_be_verified BOOLEAN NOT NULL DEFAULT TRUE, referrer_must_have_deposited BOOLEAN NOT NULL DEFAULT TRUE, min_first_deposit_raw BIGINT NOT NULL DEFAULT 0, commission_wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO referral_program_settings (id, commission_wallet_type_id) SELECT 1, id FROM wallet_types WHERE code = 'USDT_TRC20' ON CONFLICT (id) DO NOTHING; CREATE TABLE IF NOT EXISTS referral_levels ( level_number INTEGER PRIMARY KEY CHECK (level_number >= 1), commission_percent NUMERIC(8,4) NOT NULL CHECK (commission_percent >= 0 AND commission_percent <= 100), is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO referral_levels (level_number, commission_percent) VALUES (1, 20.0000), (2, 10.0000) ON CONFLICT (level_number) DO NOTHING; CREATE TABLE IF NOT EXISTS referral_commission_payouts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), beneficiary_user_id UUID NOT NULL REFERENCES users(id), referred_user_id UUID NOT NULL REFERENCES users(id), level_number INTEGER NOT NULL, first_deposit_transaction_id UUID NOT NULL REFERENCES transactions(id), deposit_amount BIGINT NOT NULL, commission_percent NUMERIC(8,4) NOT NULL, commission_amount BIGINT NOT NULL, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE (beneficiary_user_id, referred_user_id, first_deposit_transaction_id, level_number) ); CREATE INDEX IF NOT EXISTS idx_referral_payouts_beneficiary ON referral_commission_payouts(beneficiary_user_id); CREATE INDEX IF NOT EXISTS idx_referral_payouts_referred ON referral_commission_payouts(referred_user_id); CREATE TABLE IF NOT EXISTS platform_bonus_pools ( wallet_type_id INTEGER PRIMARY KEY REFERENCES wallet_types(id), available_balance BIGINT NOT NULL DEFAULT 0, updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO platform_bonus_pools (wallet_type_id) SELECT id FROM wallet_types WHERE code = 'USDT_TRC20' ON CONFLICT DO NOTHING; -- Referral commissions use a single ledger pool (USDT_TRC20). Drop stray custody-rail pools. DELETE FROM platform_bonus_pools p USING wallet_types wt WHERE p.wallet_type_id = wt.id AND wt.code <> 'USDT_TRC20'; UPDATE referral_program_settings SET commission_wallet_type_id = wt.id FROM wallet_types wt WHERE referral_program_settings.id = 1 AND wt.code = 'USDT_TRC20'; -- Extend exchange_funding for cold ↔ hot treasury moves (manual confirm workflow) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'exchange_funding' AND column_name = 'from_address' ) THEN ALTER TABLE exchange_funding ADD COLUMN from_address VARCHAR(255); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'exchange_funding' AND column_name = 'to_address' ) THEN ALTER TABLE exchange_funding ADD COLUMN to_address VARCHAR(255); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'exchange_funding' AND column_name = 'notes_encrypted' ) THEN ALTER TABLE exchange_funding ADD COLUMN notes_encrypted TEXT; END IF; END $$; INSERT INTO advertisements (placement, title, subtitle, cta_label, link_url, background_gradient, accent_color, is_active, sort_order) SELECT * FROM (VALUES ('home_hero', 'Welcome bonus', 'Deposit today and get a 100% match up to $50 on your first wallet top-up.', 'Fund wallet', '/wallet', 'linear-gradient(135deg, rgba(214,178,94,0.35) 0%, rgba(124,92,255,0.25) 100%)', '#D6B25E', TRUE, 1), ('home_hero', 'Daily spin', 'Spin the wheel every 24h for free credits and bonus multipliers.', 'Play now', '/home', 'linear-gradient(135deg, rgba(124,92,255,0.35) 0%, rgba(41,182,246,0.2) 100%)', '#7C5CFF', TRUE, 2), ('home_hero', 'Weekend tournament', 'Compete on the Candle Predict leaderboard. Top players share the prize pool.', 'Join tournament', '/games/candle-predict', 'linear-gradient(135deg, rgba(76,175,80,0.3) 0%, rgba(214,178,94,0.2) 100%)', '#4CAF50', TRUE, 3) ) AS v(placement, title, subtitle, cta_label, link_url, background_gradient, accent_color, is_active, sort_order) WHERE NOT EXISTS (SELECT 1 FROM advertisements LIMIT 1); -- Mobile home no longer shows redundant strip promos (wallet / email verify). UPDATE advertisements SET is_active = FALSE WHERE placement = 'home_strip' AND title IN ('Secure wallet', 'Verify your email'); -- Dev cleanup: remove legacy TRX / USDC wallet types (platform is USDT-only) DO $$ DECLARE legacy_ids INTEGER[]; usdt_id INTEGER; BEGIN SELECT ARRAY_AGG(id) INTO legacy_ids FROM wallet_types WHERE code IN ('TRX', 'USDC_POLYGON'); SELECT id INTO usdt_id FROM wallet_types WHERE code = 'USDT_TRC20' LIMIT 1; IF legacy_ids IS NOT NULL AND array_length(legacy_ids, 1) > 0 THEN DELETE FROM referral_commission_payouts WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM candle_predict_bets WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM withdrawal_locks WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM deposit_sweeps WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM exchange_funding WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM deposit_scanner_state WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM ledger_entries WHERE account_id IN (SELECT id FROM ledger_accounts WHERE wallet_type_id = ANY(legacy_ids)); DELETE FROM ledger_accounts WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM transactions WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM user_wallets WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM hot_wallets WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM cold_wallets WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM platform_bonus_pools WHERE wallet_type_id = ANY(legacy_ids); DELETE FROM wallet_types WHERE id = ANY(legacy_ids); END IF; IF usdt_id IS NOT NULL THEN UPDATE referral_program_settings SET commission_wallet_type_id = usdt_id WHERE id = 1; INSERT INTO platform_bonus_pools (wallet_type_id) VALUES (usdt_id) ON CONFLICT DO NOTHING; END IF; END $$; -- Denormalized admin list stats (refreshed incrementally + batch backfill) CREATE TABLE IF NOT EXISTS user_admin_stats ( user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, main_balance_raw BIGINT NOT NULL DEFAULT 0, bonus_balance_raw BIGINT NOT NULL DEFAULT 0, total_bonus_received_raw BIGINT NOT NULL DEFAULT 0, prediction_count INTEGER NOT NULL DEFAULT 0, total_stake_raw BIGINT NOT NULL DEFAULT 0, total_payout_raw BIGINT NOT NULL DEFAULT 0, net_pnl_raw BIGINT NOT NULL DEFAULT 0, last_login_at TIMESTAMPTZ, last_bet_at TIMESTAMPTZ, last_activity_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_user_admin_stats_main_balance ON user_admin_stats(main_balance_raw); CREATE INDEX IF NOT EXISTS idx_user_admin_stats_net_pnl ON user_admin_stats(net_pnl_raw); CREATE INDEX IF NOT EXISTS idx_user_admin_stats_prediction_count ON user_admin_stats(prediction_count); CREATE INDEX IF NOT EXISTS idx_user_admin_stats_bonus_received ON user_admin_stats(total_bonus_received_raw); CREATE INDEX IF NOT EXISTS idx_user_admin_stats_last_activity ON user_admin_stats(last_activity_at DESC); CREATE INDEX IF NOT EXISTS idx_user_admin_stats_last_login ON user_admin_stats(last_login_at DESC NULLS LAST); CREATE INDEX IF NOT EXISTS idx_users_created_at ON users(created_at DESC); CREATE INDEX IF NOT EXISTS idx_audit_logs_user_action_created ON audit_logs(user_id, action, created_at DESC); CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_user_type ON ledger_adjustments(user_id, adjustment_type); -- Persistent admin user export jobs (single-instance worker + local files) CREATE TABLE IF NOT EXISTS admin_export_jobs ( id UUID PRIMARY KEY, requested_by UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, status VARCHAR(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'running', 'completed', 'failed')), progress INTEGER NOT NULL DEFAULT 0, row_count INTEGER NOT NULL DEFAULT 0, total_estimate INTEGER, error TEXT, file_name VARCHAR(255), file_path TEXT, request_payload JSONB NOT NULL, format VARCHAR(8) NOT NULL DEFAULT 'xlsx' CHECK (format IN ('xlsx', 'csv', 'pdf')), max_rows INTEGER NOT NULL, columns JSONB NOT NULL, job_kind VARCHAR(16) NOT NULL DEFAULT 'users' CHECK (job_kind IN ('users', 'reports')), report_key VARCHAR(64), expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), started_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, locked_at TIMESTAMPTZ, locked_by VARCHAR(128) ); CREATE INDEX IF NOT EXISTS idx_admin_export_jobs_status_created ON admin_export_jobs(status, created_at ASC); CREATE INDEX IF NOT EXISTS idx_admin_export_jobs_requested_by ON admin_export_jobs(requested_by, created_at DESC); CREATE INDEX IF NOT EXISTS idx_admin_export_jobs_expires ON admin_export_jobs(expires_at); -- Per-user bet aggregates by game (extend with UNION ALL when new games are added) CREATE OR REPLACE VIEW user_game_bet_stats AS SELECT user_id, 'candle-predict'::varchar AS game_key, COUNT(*)::int AS bet_count, COALESCE(SUM(stake_raw), 0)::bigint AS total_stake_raw, COALESCE(SUM(payout_raw), 0)::bigint AS total_payout_raw, MAX(created_at) AS last_bet_at FROM candle_predict_bets GROUP BY user_id; -- Test wallet: play-money account kind + admin configuration CREATE TABLE IF NOT EXISTS test_wallet_settings ( id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT TRUE, credit_amount_raw BIGINT NOT NULL DEFAULT 1000000000, max_requests_per_user INTEGER NOT NULL DEFAULT 5 CHECK (max_requests_per_user >= 0), cooldown_hours INTEGER NOT NULL DEFAULT 24 CHECK (cooldown_hours >= 0), wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), prediction_limit_enabled BOOLEAN NOT NULL DEFAULT FALSE, max_test_predictions_per_window INTEGER NOT NULL DEFAULT 10 CHECK (max_test_predictions_per_window >= 0), test_prediction_window_hours INTEGER NOT NULL DEFAULT 24 CHECK (test_prediction_window_hours >= 1), updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO test_wallet_settings (id, wallet_type_id) SELECT 1, id FROM wallet_types WHERE code = 'USDT_TRC20' ON CONFLICT (id) DO NOTHING; -- Existing DBs: add Test Wallet prediction-rate-limit columns DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'test_wallet_settings' AND column_name = 'prediction_limit_enabled' ) THEN ALTER TABLE test_wallet_settings ADD COLUMN prediction_limit_enabled BOOLEAN NOT NULL DEFAULT FALSE, ADD COLUMN max_test_predictions_per_window INTEGER NOT NULL DEFAULT 10, ADD COLUMN test_prediction_window_hours INTEGER NOT NULL DEFAULT 24; ALTER TABLE test_wallet_settings ADD CONSTRAINT test_wallet_settings_max_test_predictions_per_window_check CHECK (max_test_predictions_per_window >= 0); ALTER TABLE test_wallet_settings ADD CONSTRAINT test_wallet_settings_test_prediction_window_hours_check CHECK (test_prediction_window_hours >= 1); END IF; END $$; CREATE TABLE IF NOT EXISTS test_wallet_credits ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), amount_raw BIGINT NOT NULL CHECK (amount_raw > 0), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_test_wallet_credits_user ON test_wallet_credits(user_id); CREATE INDEX IF NOT EXISTS idx_test_wallet_credits_created ON test_wallet_credits(created_at DESC); CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_user_test_created ON candle_predict_bets (user_id, created_at DESC) WHERE stake_account_kind = 'test'; -- Solo real-money encouragement bonus (exclude Test Wallet) CREATE TABLE IF NOT EXISTS solo_encouragement_settings ( id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT FALSE, min_consecutive_solo INTEGER NOT NULL DEFAULT 3 CHECK (min_consecutive_solo >= 1), refund_percent NUMERIC(8, 4) NOT NULL DEFAULT 20 CHECK (refund_percent >= 0 AND refund_percent <= 100), auto_grant BOOLEAN NOT NULL DEFAULT FALSE, wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); INSERT INTO solo_encouragement_settings (id, wallet_type_id) SELECT 1, id FROM wallet_types WHERE code = 'USDT_TRC20' ON CONFLICT (id) DO NOTHING; CREATE TABLE IF NOT EXISTS solo_encouragement_user_state ( user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, consecutive_solo_count INTEGER NOT NULL DEFAULT 0 CHECK (consecutive_solo_count >= 0), loss_raw_sum BIGINT NOT NULL DEFAULT 0 CHECK (loss_raw_sum >= 0), last_candle_open_ms BIGINT, last_bet_ids UUID[] NOT NULL DEFAULT '{}', updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS solo_encouragement_grants ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, streak_count INTEGER NOT NULL CHECK (streak_count >= 1), loss_raw BIGINT NOT NULL CHECK (loss_raw >= 0), refund_percent NUMERIC(8, 4) NOT NULL, credit_raw BIGINT NOT NULL CHECK (credit_raw >= 0), status VARCHAR(16) NOT NULL DEFAULT 'eligible' CHECK (status IN ('eligible', 'granted', 'rejected', 'skipped')), bet_ids UUID[] NOT NULL DEFAULT '{}', candle_open_ms_list BIGINT[] NOT NULL DEFAULT '{}', wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), granted_by UUID REFERENCES users(id) ON DELETE SET NULL, granted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_solo_encouragement_grants_user ON solo_encouragement_grants(user_id, created_at DESC); CREATE INDEX IF NOT EXISTS idx_solo_encouragement_grants_status ON solo_encouragement_grants(status, created_at DESC); CREATE INDEX IF NOT EXISTS idx_solo_encouragement_user_state_streak ON solo_encouragement_user_state(consecutive_solo_count DESC) WHERE consecutive_solo_count > 0; DO $$ DECLARE r RECORD; BEGIN FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'ledger_accounts'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%account_kind%' LOOP EXECUTE format('ALTER TABLE ledger_accounts DROP CONSTRAINT %I', r.conname); END LOOP; ALTER TABLE ledger_accounts ADD CONSTRAINT ledger_accounts_account_kind_check CHECK (account_kind IN ('main', 'bonus', 'test')); FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'candle_predict_bets'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%stake_account_kind%' LOOP EXECUTE format('ALTER TABLE candle_predict_bets DROP CONSTRAINT %I', r.conname); END LOOP; ALTER TABLE candle_predict_bets ADD CONSTRAINT candle_predict_bets_stake_account_kind_check CHECK (stake_account_kind IN ('main', 'bonus', 'test')); FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'candle_predict_auto_settings'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%stake_account_kind%' LOOP EXECUTE format('ALTER TABLE candle_predict_auto_settings DROP CONSTRAINT %I', r.conname); END LOOP; ALTER TABLE candle_predict_auto_settings ADD CONSTRAINT candle_predict_auto_settings_stake_account_kind_check CHECK (stake_account_kind IN ('main', 'bonus', 'test')); END $$; -- Repair test wallet ledger entries created before reference_id was linked UPDATE ledger_entries le SET reference_id = twc.id FROM ledger_accounts la JOIN test_wallet_credits twc ON twc.user_id = la.user_id AND twc.wallet_type_id = la.wallet_type_id WHERE le.account_id = la.id AND le.type = 'test_credit' AND le.reference_type = 'test_wallet_credit' AND le.reference_id IS NULL AND twc.amount_raw = le.amount AND ABS(EXTRACT(EPOCH FROM (twc.created_at - le.created_at))) < 30; -- Pool neutrality: min gap (close pools) and max imbalance (one-sided pools) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'tie_tolerance_max_percent' ) THEN ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_max_percent NUMERIC(5,2) NOT NULL DEFAULT 95.00; ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_min_enabled BOOLEAN NOT NULL DEFAULT TRUE; ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_max_enabled BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_intervals' AND column_name = 'tie_tolerance_max_percent' ) THEN ALTER TABLE candle_predict_intervals ADD COLUMN tie_tolerance_max_percent NUMERIC(5,2); ALTER TABLE candle_predict_intervals ADD COLUMN tie_tolerance_min_enabled BOOLEAN; ALTER TABLE candle_predict_intervals ADD COLUMN tie_tolerance_max_enabled BOOLEAN; END IF; END $$; -- User gender (male, female, other) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'gender' ) THEN ALTER TABLE users ADD COLUMN gender VARCHAR(10) CHECK (gender IN ('male', 'female', 'other')); END IF; END $$; -- Migration: extend admin_export_jobs for async report exports (existing DBs) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'admin_export_jobs' AND column_name = 'job_kind' ) THEN ALTER TABLE admin_export_jobs ADD COLUMN job_kind VARCHAR(16) NOT NULL DEFAULT 'users'; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'admin_export_jobs' AND column_name = 'report_key' ) THEN ALTER TABLE admin_export_jobs ADD COLUMN report_key VARCHAR(64); END IF; END $$; ALTER TABLE admin_export_jobs DROP CONSTRAINT IF EXISTS admin_export_jobs_format_check; ALTER TABLE admin_export_jobs ADD CONSTRAINT admin_export_jobs_format_check CHECK (format IN ('xlsx', 'csv', 'pdf')); ALTER TABLE admin_export_jobs DROP CONSTRAINT IF EXISTS admin_export_jobs_job_kind_check; ALTER TABLE admin_export_jobs ADD CONSTRAINT admin_export_jobs_job_kind_check CHECK (job_kind IN ('users', 'reports')); -- Scalability: indexes for high-volume report/analytics queries CREATE INDEX IF NOT EXISTS idx_transactions_type_status_created ON transactions(type, status, created_at DESC); CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_created_at ON candle_predict_bets(created_at DESC); CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_user_created ON candle_predict_bets(user_id, created_at DESC); CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_created_at ON ledger_adjustments(created_at DESC); -- Daily rollups for dashboard acceleration (refreshed by background job) CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_transactions AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, type, status, COUNT(*)::bigint AS tx_count, COALESCE(SUM(amount), 0)::bigint AS amount_raw, COALESCE(MAX(amount), 0)::bigint AS max_amount_raw FROM transactions GROUP BY 1, 2, 3; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_transactions_pk ON analytics_daily_transactions(day, type, status); -- Rebuild bets MV when chart dimensions (direction, interval) are missing DO $$ BEGIN IF EXISTS ( SELECT 1 FROM pg_matviews WHERE schemaname = 'public' AND matviewname = 'analytics_daily_bets' ) AND NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'analytics_daily_bets' AND column_name = 'direction' ) THEN DROP MATERIALIZED VIEW analytics_daily_bets; END IF; END $$; CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_bets AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, is_auto, stake_account_kind, status, direction, interval_minutes, COUNT(*)::bigint AS bet_count, COALESCE(SUM(stake_raw), 0)::bigint AS stake_raw, COALESCE(SUM(payout_raw), 0)::bigint AS payout_raw FROM candle_predict_bets GROUP BY 1, 2, 3, 4, 5, 6; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_bets_pk ON analytics_daily_bets(day, is_auto, stake_account_kind, status, direction, interval_minutes); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_adjustments AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, adjustment_type, COUNT(*)::bigint AS adj_count, COALESCE(SUM(amount), 0)::bigint AS amount_raw FROM ledger_adjustments GROUP BY 1, 2; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_adjustments_pk ON analytics_daily_adjustments(day, adjustment_type); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_hourly_bets AS SELECT date_trunc('hour', created_at AT TIME ZONE 'UTC') AS hour_ts, COUNT(*)::bigint AS bet_count FROM candle_predict_bets GROUP BY 1; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_hourly_bets_pk ON analytics_hourly_bets(hour_ts); -- Extend transactions MV with max amount for KPI queries (existing DBs) DO $$ BEGIN IF EXISTS ( SELECT 1 FROM pg_matviews WHERE schemaname = 'public' AND matviewname = 'analytics_daily_transactions' ) AND NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'analytics_daily_transactions' AND column_name = 'max_amount_raw' ) THEN DROP MATERIALIZED VIEW analytics_daily_transactions; END IF; END $$; CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_transactions AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, type, status, COUNT(*)::bigint AS tx_count, COALESCE(SUM(amount), 0)::bigint AS amount_raw, COALESCE(MAX(amount), 0)::bigint AS max_amount_raw FROM transactions GROUP BY 1, 2, 3; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_transactions_pk ON analytics_daily_transactions(day, type, status); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_tx_by_user AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, type, status, user_id, COUNT(*)::bigint AS tx_count, COALESCE(SUM(amount), 0)::bigint AS amount_raw FROM transactions WHERE status = 'completed' AND type IN ('deposit', 'withdrawal') GROUP BY 1, 2, 3, 4; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_tx_by_user_pk ON analytics_daily_tx_by_user(day, type, status, user_id); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_tx_by_country AS SELECT date_trunc('day', t.created_at AT TIME ZONE 'UTC')::date AS day, COALESCE(u.country_of_residence, 'XX') AS country, t.type, COUNT(*)::bigint AS tx_count, COALESCE(SUM(t.amount), 0)::bigint AS amount_raw FROM transactions t JOIN users u ON u.id = t.user_id WHERE t.status = 'completed' AND t.type IN ('deposit', 'withdrawal') GROUP BY 1, 2, 3; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_tx_by_country_pk ON analytics_daily_tx_by_country(day, country, type); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_bets_by_user AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, user_id, is_auto, stake_account_kind, COUNT(*)::bigint AS bet_count, COALESCE(SUM(stake_raw), 0)::bigint AS stake_raw, COALESCE(SUM(payout_raw), 0)::bigint AS payout_raw, SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END)::bigint AS won_count, SUM(CASE WHEN status IN ('won', 'lost') THEN 1 ELSE 0 END)::bigint AS settled_count FROM candle_predict_bets GROUP BY 1, 2, 3, 4; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_bets_by_user_pk ON analytics_daily_bets_by_user(day, user_id, is_auto, stake_account_kind); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_adjustments_by_user AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, adjustment_type, user_id, COUNT(*)::bigint AS adj_count, COALESCE(SUM(amount), 0)::bigint AS amount_raw FROM ledger_adjustments GROUP BY 1, 2, 3; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_adjustments_by_user_pk ON analytics_daily_adjustments_by_user(day, adjustment_type, user_id); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_referrals_by_user AS SELECT date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day, beneficiary_user_id AS user_id, COUNT(*)::bigint AS payout_count, COALESCE(SUM(commission_amount), 0)::bigint AS amount_raw FROM referral_commission_payouts GROUP BY 1, 2; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_referrals_by_user_pk ON analytics_daily_referrals_by_user(day, user_id); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_country_user_logins AS SELECT date_trunc('day', al.created_at AT TIME ZONE 'UTC')::date AS day, COALESCE(u.country_of_residence, 'XX') AS country, al.user_id FROM audit_logs al JOIN users u ON u.id = al.user_id WHERE al.action = 'login' GROUP BY 1, 2, 3; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_country_user_logins_pk ON analytics_daily_country_user_logins(day, country, user_id); CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_active_users AS SELECT day, user_id FROM ( SELECT date_trunc('day', al.created_at AT TIME ZONE 'UTC')::date AS day, al.user_id FROM audit_logs al WHERE al.action = 'login' UNION SELECT date_trunc('day', b.created_at AT TIME ZONE 'UTC')::date, b.user_id FROM candle_predict_bets b ) active GROUP BY day, user_id; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_active_users_pk ON analytics_daily_active_users(day, user_id); -- Modular prediction types & multi-candle prediction DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'prediction_single_enabled' ) THEN ALTER TABLE candle_predict_config ADD COLUMN prediction_single_enabled BOOLEAN NOT NULL DEFAULT TRUE; ALTER TABLE candle_predict_config ADD COLUMN prediction_auto_enabled BOOLEAN NOT NULL DEFAULT TRUE; ALTER TABLE candle_predict_config ADD COLUMN prediction_multi_enabled BOOLEAN NOT NULL DEFAULT TRUE; END IF; END $$; -- Daily revenue target outcome mode (independent of majority/minority) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'daily_revenue_target' ) THEN ALTER TABLE candle_predict_config ADD COLUMN daily_revenue_target NUMERIC(18,6) NOT NULL DEFAULT 0; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'daily_revenue_overflow_strategy' ) THEN ALTER TABLE candle_predict_config ADD COLUMN daily_revenue_overflow_strategy VARCHAR(16) NOT NULL DEFAULT 'neutral'; END IF; END $$; CREATE TABLE IF NOT EXISTS candle_predict_daily_revenue ( revenue_date DATE PRIMARY KEY, net_pnl_raw NUMERIC(28,0) NOT NULL DEFAULT 0, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS candle_predict_multi_levels ( level SMALLINT PRIMARY KEY CHECK (level >= 2 AND level <= 20), enabled BOOLEAN NOT NULL DEFAULT TRUE, -- Payout multiplier: win payout when the full sequence is correct. payout_multiplier NUMERIC(8,3) NOT NULL DEFAULT 1 CHECK (payout_multiplier > 0), -- Pool multiplier: stake weight in Long/Short pools at the final candle only. pool_multiplier NUMERIC(8,3) NOT NULL DEFAULT 1 CHECK (pool_multiplier > 0), sort_order INTEGER NOT NULL DEFAULT 0, updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Separate pool_multiplier from payout_multiplier (pools vs win payout). -- Must run before seed INSERT below (existing DBs lack this column until migrated). DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'pool_multiplier' ) THEN ALTER TABLE candle_predict_config ADD COLUMN pool_multiplier NUMERIC(6,3); UPDATE candle_predict_config SET pool_multiplier = payout_multiplier WHERE pool_multiplier IS NULL; ALTER TABLE candle_predict_config ALTER COLUMN pool_multiplier SET NOT NULL; ALTER TABLE candle_predict_config ALTER COLUMN pool_multiplier SET DEFAULT 1.900; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_intervals' AND column_name = 'pool_multiplier' ) THEN ALTER TABLE candle_predict_intervals ADD COLUMN pool_multiplier NUMERIC(6,3); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_multi_levels' AND column_name = 'pool_multiplier' ) THEN ALTER TABLE candle_predict_multi_levels ADD COLUMN pool_multiplier NUMERIC(8,3); UPDATE candle_predict_multi_levels SET pool_multiplier = payout_multiplier WHERE pool_multiplier IS NULL; ALTER TABLE candle_predict_multi_levels ALTER COLUMN pool_multiplier SET NOT NULL; ALTER TABLE candle_predict_multi_levels ALTER COLUMN pool_multiplier SET DEFAULT 1; IF NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conname = 'candle_predict_multi_levels_pool_multiplier_check' ) THEN ALTER TABLE candle_predict_multi_levels ADD CONSTRAINT candle_predict_multi_levels_pool_multiplier_check CHECK (pool_multiplier > 0); END IF; END IF; END $$; INSERT INTO candle_predict_multi_levels (level, enabled, payout_multiplier, pool_multiplier, sort_order) VALUES (2, TRUE, 3, 3, 1), (3, TRUE, 6, 6, 2), (4, TRUE, 10, 10, 3), (5, TRUE, 15, 15, 4) ON CONFLICT (level) DO NOTHING; DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_bets' AND column_name = 'prediction_mode' ) THEN ALTER TABLE candle_predict_bets ADD COLUMN prediction_mode VARCHAR(24) NOT NULL DEFAULT 'single'; ALTER TABLE candle_predict_bets ADD COLUMN sequence_directions JSONB; ALTER TABLE candle_predict_bets ADD COLUMN multi_level SMALLINT; ALTER TABLE candle_predict_bets ADD COLUMN sequence_step SMALLINT NOT NULL DEFAULT 0; ALTER TABLE candle_predict_bets ADD COLUMN anchor_candle_open_ms BIGINT; END IF; END $$; UPDATE candle_predict_bets SET prediction_mode = 'single' WHERE prediction_mode IS NULL OR prediction_mode = ''; ALTER TABLE candle_predict_bets DROP CONSTRAINT IF EXISTS candle_predict_bets_round_id_user_id_key; CREATE UNIQUE INDEX IF NOT EXISTS uq_candle_bets_single_per_round_user ON candle_predict_bets(round_id, user_id) WHERE prediction_mode = 'single'; CREATE UNIQUE INDEX IF NOT EXISTS uq_candle_bets_one_active_multi_per_user_interval ON candle_predict_bets(user_id, interval_minutes) WHERE prediction_mode = 'multi_candle' AND status = 'in_progress'; CREATE INDEX IF NOT EXISTS idx_candle_bets_multi_validation ON candle_predict_bets(anchor_candle_open_ms, interval_minutes, sequence_step) WHERE prediction_mode = 'multi_candle' AND status = 'in_progress'; DO $$ DECLARE r RECORD; BEGIN FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'candle_predict_bets'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%status%' LOOP EXECUTE format('ALTER TABLE candle_predict_bets DROP CONSTRAINT %I', r.conname); END LOOP; ALTER TABLE candle_predict_bets ADD CONSTRAINT candle_predict_bets_status_check CHECK (status IN ('pending', 'in_progress', 'won', 'lost', 'refunded')); END $$; -- Referral anti-fraud: deferred commissions and referred-user eligibility DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'referred_must_be_verified' ) THEN ALTER TABLE referral_program_settings ADD COLUMN referred_must_be_verified BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'commission_hold_days' ) THEN ALTER TABLE referral_program_settings ADD COLUMN commission_hold_days INTEGER NOT NULL DEFAULT 14 CHECK (commission_hold_days >= 0); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'min_referred_predictions' ) THEN ALTER TABLE referral_program_settings ADD COLUMN min_referred_predictions INTEGER NOT NULL DEFAULT 10 CHECK (min_referred_predictions >= 0); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'commission_max_pending_days' ) THEN ALTER TABLE referral_program_settings ADD COLUMN commission_max_pending_days INTEGER NOT NULL DEFAULT 90 CHECK (commission_max_pending_days >= 1); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts' AND column_name = 'status' ) THEN ALTER TABLE referral_commission_payouts ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'pending'; ALTER TABLE referral_commission_payouts ADD COLUMN eligible_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); ALTER TABLE referral_commission_payouts ADD COLUMN paid_at TIMESTAMPTZ; ALTER TABLE referral_commission_payouts ADD COLUMN rejection_reason TEXT; ALTER TABLE referral_commission_payouts ADD COLUMN updated_at TIMESTAMPTZ DEFAULT NOW(); UPDATE referral_commission_payouts SET status = 'paid', paid_at = created_at, eligible_at = created_at, updated_at = created_at; END IF; END $$; DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conname = 'referral_commission_payouts_status_check' ) THEN ALTER TABLE referral_commission_payouts ADD CONSTRAINT referral_commission_payouts_status_check CHECK (status IN ('pending', 'paid', 'rejected', 'expired')); END IF; END $$; CREATE INDEX IF NOT EXISTS idx_referral_payouts_pending ON referral_commission_payouts(eligible_at) WHERE status = 'pending'; DROP MATERIALIZED VIEW IF EXISTS analytics_daily_referrals_by_user; CREATE MATERIALIZED VIEW analytics_daily_referrals_by_user AS SELECT date_trunc('day', COALESCE(paid_at, created_at) AT TIME ZONE 'UTC')::date AS day, beneficiary_user_id AS user_id, COUNT(*)::bigint AS payout_count, COALESCE(SUM(commission_amount), 0)::bigint AS amount_raw FROM referral_commission_payouts WHERE status = 'paid' GROUP BY 1, 2; CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_referrals_by_user_pk ON analytics_daily_referrals_by_user(day, user_id); -- Referral anti-fraud P2: Sybil detection, manual review queue, registration IP DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'registration_ip' ) THEN ALTER TABLE users ADD COLUMN registration_ip VARCHAR(45); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'sybil_detection_enabled' ) THEN ALTER TABLE referral_program_settings ADD COLUMN sybil_detection_enabled BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'sybil_review_threshold' ) THEN ALTER TABLE referral_program_settings ADD COLUMN sybil_review_threshold INTEGER NOT NULL DEFAULT 3 CHECK (sybil_review_threshold >= 0); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'sybil_block_threshold' ) THEN ALTER TABLE referral_program_settings ADD COLUMN sybil_block_threshold INTEGER NOT NULL DEFAULT 5 CHECK (sybil_block_threshold >= 1); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'max_referrals_per_day' ) THEN ALTER TABLE referral_program_settings ADD COLUMN max_referrals_per_day INTEGER NOT NULL DEFAULT 10 CHECK (max_referrals_per_day >= 1); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts' AND column_name = 'sybil_score' ) THEN ALTER TABLE referral_commission_payouts ADD COLUMN sybil_score INTEGER NOT NULL DEFAULT 0; ALTER TABLE referral_commission_payouts ADD COLUMN sybil_signals JSONB NOT NULL DEFAULT '[]'::jsonb; ALTER TABLE referral_commission_payouts ADD COLUMN reviewed_by UUID REFERENCES users(id); ALTER TABLE referral_commission_payouts ADD COLUMN reviewed_at TIMESTAMPTZ; ALTER TABLE referral_commission_payouts ADD COLUMN review_note TEXT; END IF; END $$; DO $$ BEGIN IF EXISTS ( SELECT 1 FROM pg_constraint WHERE conname = 'referral_commission_payouts_status_check' ) THEN ALTER TABLE referral_commission_payouts DROP CONSTRAINT referral_commission_payouts_status_check; END IF; ALTER TABLE referral_commission_payouts ADD CONSTRAINT referral_commission_payouts_status_check CHECK (status IN ('pending', 'review', 'paid', 'rejected', 'expired')); EXCEPTION WHEN duplicate_object THEN NULL; END $$; CREATE INDEX IF NOT EXISTS idx_users_registration_ip ON users(registration_ip) WHERE registration_ip IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_audit_logs_ip ON audit_logs(ip_address) WHERE ip_address IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_referral_payouts_review ON referral_commission_payouts(created_at DESC) WHERE status = 'review'; -- Referral anti-fraud P3: monthly caps, clawbacks, fraud audit DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'max_commission_amount_per_referrer_month_raw' ) THEN ALTER TABLE referral_program_settings ADD COLUMN max_commission_amount_per_referrer_month_raw BIGINT NOT NULL DEFAULT 500000000; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'max_commissions_per_referrer_month' ) THEN ALTER TABLE referral_program_settings ADD COLUMN max_commissions_per_referrer_month INTEGER NOT NULL DEFAULT 50 CHECK (max_commissions_per_referrer_month >= 0); END IF; END $$; CREATE TABLE IF NOT EXISTS referral_commission_clawbacks ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), payout_id UUID NOT NULL REFERENCES referral_commission_payouts(id), beneficiary_user_id UUID NOT NULL REFERENCES users(id), amount BIGINT NOT NULL CHECK (amount > 0), reason TEXT NOT NULL, clawed_by UUID NOT NULL REFERENCES users(id), created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_referral_clawbacks_payout ON referral_commission_clawbacks(payout_id); CREATE INDEX IF NOT EXISTS idx_referral_clawbacks_beneficiary ON referral_commission_clawbacks(beneficiary_user_id); CREATE INDEX IF NOT EXISTS idx_referral_clawbacks_created ON referral_commission_clawbacks(created_at DESC); DO $$ BEGIN IF EXISTS ( SELECT 1 FROM pg_constraint WHERE conname = 'referral_commission_payouts_status_check' ) THEN ALTER TABLE referral_commission_payouts DROP CONSTRAINT referral_commission_payouts_status_check; END IF; ALTER TABLE referral_commission_payouts ADD CONSTRAINT referral_commission_payouts_status_check CHECK (status IN ('pending', 'review', 'paid', 'rejected', 'expired', 'clawed_back')); EXCEPTION WHEN duplicate_object THEN NULL; END $$; CREATE INDEX IF NOT EXISTS idx_referral_payouts_beneficiary_month ON referral_commission_payouts(beneficiary_user_id, created_at DESC); -- Referral refinements: per-MLM-level monthly caps + Slack toggle DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_levels' AND column_name = 'monthly_max_amount_raw' ) THEN ALTER TABLE referral_levels ADD COLUMN monthly_max_amount_raw BIGINT NOT NULL DEFAULT 0; ALTER TABLE referral_levels ADD COLUMN monthly_max_count INTEGER NOT NULL DEFAULT 0 CHECK (monthly_max_count >= 0); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'slack_alerts_enabled' ) THEN ALTER TABLE referral_program_settings ADD COLUMN slack_alerts_enabled BOOLEAN NOT NULL DEFAULT TRUE; END IF; END $$; -- Dual commission modes (deposit + withdrawal) and payout source tracking DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'deposit_commissions_enabled' ) THEN ALTER TABLE referral_program_settings ADD COLUMN deposit_commissions_enabled BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE referral_program_settings ADD COLUMN withdrawal_commissions_enabled BOOLEAN NOT NULL DEFAULT FALSE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts' AND column_name = 'commission_source' ) THEN ALTER TABLE referral_commission_payouts ADD COLUMN commission_source VARCHAR(20) NOT NULL DEFAULT 'deposit' CHECK (commission_source IN ('deposit', 'withdrawal')); ALTER TABLE referral_commission_payouts ADD COLUMN withdrawal_transaction_id UUID REFERENCES transactions(id); ALTER TABLE referral_commission_payouts ALTER COLUMN first_deposit_transaction_id DROP NOT NULL; END IF; END $$; DO $$ DECLARE r record; BEGIN FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'public.referral_commission_payouts'::regclass AND contype = 'u' LOOP EXECUTE format('ALTER TABLE referral_commission_payouts DROP CONSTRAINT %I', r.conname); END LOOP; END $$; CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_deposit_unique ON referral_commission_payouts (beneficiary_user_id, referred_user_id, first_deposit_transaction_id, level_number) WHERE commission_source = 'deposit' AND first_deposit_transaction_id IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_withdrawal_unique ON referral_commission_payouts (beneficiary_user_id, referred_user_id, withdrawal_transaction_id, level_number) WHERE commission_source = 'withdrawal' AND withdrawal_transaction_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_referral_payouts_withdrawal_tx ON referral_commission_payouts (withdrawal_transaction_id) WHERE withdrawal_transaction_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_referral_payouts_referred_source ON referral_commission_payouts (referred_user_id, commission_source); -- Integrated support messaging (users, visitors, staff) CREATE TABLE IF NOT EXISTS support_conversations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES users(id) ON DELETE SET NULL, visitor_token VARCHAR(64), subject VARCHAR(255), status VARCHAR(20) NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'pending', 'resolved', 'closed')), assigned_to UUID REFERENCES users(id) ON DELETE SET NULL, last_message_at TIMESTAMPTZ, last_message_preview VARCHAR(500), unread_user INTEGER NOT NULL DEFAULT 0, unread_staff INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CHECK (user_id IS NOT NULL OR (visitor_token IS NOT NULL AND length(visitor_token) >= 16)) ); CREATE INDEX IF NOT EXISTS idx_support_conv_user ON support_conversations(user_id) WHERE user_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_support_conv_visitor ON support_conversations(visitor_token) WHERE visitor_token IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_support_conv_status ON support_conversations(status, last_message_at DESC NULLS LAST); CREATE INDEX IF NOT EXISTS idx_support_conv_assigned ON support_conversations(assigned_to) WHERE assigned_to IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_support_conv_last_msg ON support_conversations(last_message_at DESC NULLS LAST); CREATE TABLE IF NOT EXISTS support_messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id UUID NOT NULL REFERENCES support_conversations(id) ON DELETE CASCADE, sender_type VARCHAR(10) NOT NULL CHECK (sender_type IN ('user', 'visitor', 'staff')), sender_user_id UUID REFERENCES users(id) ON DELETE SET NULL, body TEXT, attachment_url VARCHAR(512), attachment_name VARCHAR(255), attachment_mime VARCHAR(128), read_at TIMESTAMPTZ, edited_at TIMESTAMPTZ, deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CHECK (body IS NOT NULL OR attachment_url IS NOT NULL OR deleted_at IS NOT NULL) ); DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'support_messages' AND column_name = 'edited_at' ) THEN ALTER TABLE support_messages ADD COLUMN edited_at TIMESTAMPTZ; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'support_messages' AND column_name = 'deleted_at' ) THEN ALTER TABLE support_messages ADD COLUMN deleted_at TIMESTAMPTZ; END IF; END $$; INSERT INTO system_settings (key, value) VALUES ('support_message_edit_window_minutes', '15'), ('support_message_delete_window_minutes', '15') ON CONFLICT (key) DO NOTHING; CREATE INDEX IF NOT EXISTS idx_support_msg_conv ON support_messages(conversation_id, created_at ASC); CREATE INDEX IF NOT EXISTS idx_support_msg_unread ON support_messages(conversation_id, read_at) WHERE read_at IS NULL; -- FAQ (categories + entries, staff-managed) CREATE TABLE IF NOT EXISTS faq_categories ( id SERIAL PRIMARY KEY, slug VARCHAR(64) NOT NULL UNIQUE, name VARCHAR(128) NOT NULL, sort_order INTEGER NOT NULL DEFAULT 0, is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS faq_entries ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), category_id INTEGER NOT NULL REFERENCES faq_categories(id) ON DELETE RESTRICT, question VARCHAR(512) NOT NULL, answer_html TEXT NOT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE, sort_order INTEGER NOT NULL DEFAULT 0, view_count INTEGER NOT NULL DEFAULT 0, helpful_yes INTEGER NOT NULL DEFAULT 0, helpful_no INTEGER NOT NULL DEFAULT 0, created_by UUID REFERENCES users(id) ON DELETE SET NULL, updated_by UUID REFERENCES users(id) ON DELETE SET NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_faq_entries_category ON faq_entries(category_id, sort_order); CREATE INDEX IF NOT EXISTS idx_faq_entries_active ON faq_entries(is_active, sort_order); CREATE INDEX IF NOT EXISTS idx_faq_entries_popular ON faq_entries(view_count DESC) WHERE is_active = TRUE; CREATE TABLE IF NOT EXISTS faq_helpful_votes ( faq_id UUID NOT NULL REFERENCES faq_entries(id) ON DELETE CASCADE, voter_key VARCHAR(128) NOT NULL, helpful BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (faq_id, voter_key) ); INSERT INTO faq_categories (slug, name, sort_order) VALUES ('account', 'Compte', 1), ('deposits', 'Dépôts', 2), ('withdrawals', 'Retraits', 3), ('predictions', 'Prédictions', 4), ('referral', 'Parrainage', 5), ('bonus', 'Bonus', 6), ('security', 'Sécurité', 7) ON CONFLICT (slug) DO NOTHING; -- ============================================================================= -- Database tamper detection (direct SQL / bypass application) -- ============================================================================= CREATE TABLE IF NOT EXISTS db_tamper_events ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), table_name VARCHAR(128) NOT NULL, operation VARCHAR(16) NOT NULL CHECK (operation IN ('INSERT', 'UPDATE', 'DELETE')), row_id TEXT, old_data JSONB, new_data JSONB, changed_columns TEXT[], source_hint VARCHAR(64) NOT NULL DEFAULT 'direct_database_access', severity VARCHAR(20) NOT NULL DEFAULT 'high' CHECK (severity IN ('low', 'medium', 'high', 'critical')), processed_at TIMESTAMPTZ, security_alert_id UUID REFERENCES security_alerts(id) ON DELETE SET NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_db_tamper_events_unprocessed ON db_tamper_events(created_at ASC) WHERE processed_at IS NULL; CREATE INDEX IF NOT EXISTS idx_db_tamper_events_table ON db_tamper_events(table_name, created_at DESC); CREATE OR REPLACE FUNCTION fn_redact_tamper_row(tbl TEXT, data JSONB) RETURNS JSONB AS $$ DECLARE result JSONB := data; BEGIN IF result IS NULL THEN RETURN NULL; END IF; IF tbl = 'hot_wallets' AND result ? 'encrypted_private_key' THEN result := result - 'encrypted_private_key' || jsonb_build_object('encrypted_private_key', '[REDACTED]'); END IF; IF tbl = 'users' THEN IF result ? 'password_hash' THEN result := result - 'password_hash' || jsonb_build_object('password_hash', '[REDACTED]'); END IF; IF result ? 'totp_secret_encrypted' THEN result := result - 'totp_secret_encrypted' || jsonb_build_object('totp_secret_encrypted', '[REDACTED]'); END IF; IF result ? 'email_encrypted' THEN result := result - 'email_encrypted' || jsonb_build_object('email_encrypted', '[REDACTED]'); END IF; IF result ? 'phone_encrypted' THEN result := result - 'phone_encrypted' || jsonb_build_object('phone_encrypted', '[REDACTED]'); END IF; END IF; RETURN result; END; $$ LANGUAGE plpgsql IMMUTABLE; CREATE OR REPLACE FUNCTION fn_db_tamper_row_id(tbl TEXT, row_data JSONB) RETURNS TEXT AS $$ BEGIN IF row_data IS NULL THEN RETURN NULL; END IF; IF row_data ? 'id' THEN RETURN row_data ->> 'id'; END IF; IF tbl = 'system_settings' AND row_data ? 'key' THEN RETURN row_data ->> 'key'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql IMMUTABLE; CREATE OR REPLACE FUNCTION fn_db_tamper_changed_columns(old_row JSONB, new_row JSONB) RETURNS TEXT[] AS $$ SELECT COALESCE(array_agg(key ORDER BY key), ARRAY[]::TEXT[]) FROM ( SELECT key FROM jsonb_each(COALESCE(new_row, '{}'::jsonb)) UNION SELECT key FROM jsonb_each(COALESCE(old_row, '{}'::jsonb)) ) keys(key) WHERE COALESCE(new_row -> key, 'null'::jsonb) IS DISTINCT FROM COALESCE(old_row -> key, 'null'::jsonb); $$ LANGUAGE sql IMMUTABLE; CREATE OR REPLACE FUNCTION fn_db_tamper_base_severity(tbl TEXT) RETURNS VARCHAR(20) AS $$ BEGIN RETURN CASE tbl WHEN 'hot_wallets' THEN 'critical' WHEN 'cold_wallets' THEN 'critical' WHEN 'roles' THEN 'critical' WHEN 'ledger_entries' THEN 'critical' WHEN 'ledger_accounts' THEN 'critical' WHEN 'transactions' THEN 'critical' WHEN 'ledger_adjustments' THEN 'high' WHEN 'users' THEN 'high' WHEN 'candle_predict_config' THEN 'high' WHEN 'candle_predict_intervals' THEN 'high' WHEN 'candle_predict_multi_levels' THEN 'high' WHEN 'candle_predict_bets' THEN 'high' WHEN 'candle_predict_rounds' THEN 'high' WHEN 'test_wallet_credits' THEN 'high' WHEN 'test_wallet_settings' THEN 'high' WHEN 'solo_encouragement_settings' THEN 'high' WHEN 'solo_encouragement_grants' THEN 'high' WHEN 'share_card_settings' THEN 'medium' WHEN 'referral_program_settings' THEN 'high' WHEN 'platform_bonus_pools' THEN 'high' WHEN 'exchange_funding' THEN 'high' WHEN 'fund_operation_requests' THEN 'critical' WHEN 'user_roles' THEN 'critical' WHEN 'role_permissions' THEN 'critical' WHEN 'permissions' THEN 'critical' WHEN 'deposit_sweep_batches' THEN 'high' WHEN 'system_settings' THEN 'medium' WHEN 'withdrawal_locks' THEN 'medium' WHEN 'deposit_scanner_state' THEN 'medium' WHEN 'security_alerts' THEN 'high' WHEN 'refresh_tokens' THEN 'medium' WHEN 'user_wallets' THEN 'high' WHEN 'deposit_sweeps' THEN 'high' WHEN 'faq_entries' THEN 'medium' WHEN 'faq_categories' THEN 'medium' WHEN 'referral_commission_payouts' THEN 'high' WHEN 'games' THEN 'medium' ELSE 'medium' END; END; $$ LANGUAGE plpgsql IMMUTABLE; CREATE OR REPLACE FUNCTION trg_fn_db_tamper_guard() RETURNS TRIGGER AS $$ DECLARE authorized TEXT; old_j JSONB; new_j JSONB; cols TEXT[]; sev VARCHAR(20); row_pk TEXT; BEGIN -- Application legitimately inserts alerts/notifications; only tampering updates/deletes matter. IF TG_TABLE_NAME IN ('security_alerts', 'admin_notifications') AND TG_OP = 'INSERT' THEN IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END IF; authorized := current_setting('app.authorized_change', true); IF authorized IN ('1', 'true', 'yes') THEN IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END IF; IF TG_OP = 'INSERT' THEN old_j := NULL; new_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(NEW)); cols := fn_db_tamper_changed_columns(NULL, new_j); ELSIF TG_OP = 'UPDATE' THEN old_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(OLD)); new_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(NEW)); cols := fn_db_tamper_changed_columns(old_j, new_j); IF cols = ARRAY[]::TEXT[] THEN RETURN NEW; END IF; ELSE old_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(OLD)); new_j := NULL; cols := fn_db_tamper_changed_columns(old_j, NULL); END IF; sev := fn_db_tamper_base_severity(TG_TABLE_NAME); row_pk := fn_db_tamper_row_id(TG_TABLE_NAME, COALESCE(new_j, old_j)); IF TG_TABLE_NAME = 'users' AND TG_OP = 'INSERT' THEN sev := 'critical'; ELSIF TG_TABLE_NAME = 'users' AND TG_OP = 'UPDATE' AND ( 'role_id' = ANY(cols) OR 'password_hash' = ANY(cols) OR 'withdrawals_suspended' = ANY(cols) OR 'under_surveillance' = ANY(cols) OR 'is_enabled' = ANY(cols) ) THEN sev := 'critical'; ELSIF TG_TABLE_NAME = 'transactions' AND TG_OP = 'DELETE' THEN sev := 'critical'; ELSIF TG_TABLE_NAME = 'ledger_accounts' AND ( 'available_balance' = ANY(cols) OR 'locked_balance' = ANY(cols) ) THEN sev := 'critical'; ELSIF TG_TABLE_NAME = 'user_wallets' AND ( 'address' = ANY(cols) OR 'derivation_index' = ANY(cols) ) THEN sev := 'critical'; ELSIF TG_TABLE_NAME = 'deposit_sweeps' AND ( 'amount' = ANY(cols) OR 'status' = ANY(cols) OR 'blockchain_tx_id' = ANY(cols) ) THEN sev := 'critical'; END IF; INSERT INTO db_tamper_events ( table_name, operation, row_id, old_data, new_data, changed_columns, source_hint, severity ) VALUES ( TG_TABLE_NAME, TG_OP, row_pk, old_j, new_j, cols, 'direct_database_access', sev ); IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; -- P1 security: login lockout columns, TOTP recovery codes, settings (before tamper triggers) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'failed_login_count' ) THEN ALTER TABLE users ADD COLUMN failed_login_count INTEGER NOT NULL DEFAULT 0; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'login_locked_until' ) THEN ALTER TABLE users ADD COLUMN login_locked_until TIMESTAMPTZ; END IF; END $$; CREATE TABLE IF NOT EXISTS user_totp_recovery_codes ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, code_hash VARCHAR(64) NOT NULL, used_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_totp_recovery_user ON user_totp_recovery_codes(user_id); CREATE UNIQUE INDEX IF NOT EXISTS idx_totp_recovery_code_hash ON user_totp_recovery_codes(user_id, code_hash); INSERT INTO system_settings (key, value) VALUES ('require_admin_2fa', 'true'), ('login_max_failed_attempts', '5'), ('login_lockout_minutes', '15'), ('login_captcha_after_failures', '3') ON CONFLICT (key) DO NOTHING; CREATE TABLE IF NOT EXISTS user_login_fingerprints ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, ip_address VARCHAR(45) NOT NULL, user_agent_hash VARCHAR(64) NOT NULL, country_code CHAR(2), first_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), UNIQUE (user_id, ip_address, user_agent_hash) ); CREATE INDEX IF NOT EXISTS idx_login_fingerprints_user ON user_login_fingerprints(user_id); DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'user_login_fingerprints' AND column_name = 'country_code' ) THEN ALTER TABLE user_login_fingerprints ADD COLUMN country_code CHAR(2); END IF; END $$; CREATE TABLE IF NOT EXISTS user_security_notifications ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, event_type VARCHAR(64) NOT NULL, title VARCHAR(255) NOT NULL, body TEXT, read_at TIMESTAMPTZ, metadata JSONB, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_user_security_notifications_user ON user_security_notifications(user_id, created_at DESC); CREATE INDEX IF NOT EXISTS idx_user_security_notifications_unread ON user_security_notifications(user_id) WHERE read_at IS NULL; DO $$ DECLARE tbl TEXT; BEGIN FOREACH tbl IN ARRAY ARRAY[ 'users', 'roles', 'ledger_accounts', 'ledger_entries', 'transactions', 'hot_wallets', 'cold_wallets', 'ledger_adjustments', 'candle_predict_config', 'candle_predict_intervals', 'candle_predict_multi_levels', 'candle_predict_bets', 'candle_predict_rounds', 'candle_predict_daily_revenue', 'test_wallet_credits', 'test_wallet_settings', 'solo_encouragement_settings', 'solo_encouragement_user_state', 'solo_encouragement_grants', 'referral_program_settings', 'platform_bonus_pools', 'exchange_funding', 'system_settings', 'withdrawal_locks', 'deposit_scanner_state', 'security_alerts', 'refresh_tokens', 'user_wallets', 'deposit_sweeps', 'faq_entries', 'faq_categories', 'referral_commission_payouts', 'games', 'fund_operation_requests', 'user_roles', 'role_permissions', 'permissions', 'deposit_sweep_batches', 'user_totp_recovery_codes' ] LOOP EXECUTE format('DROP TRIGGER IF EXISTS trg_db_tamper_%I ON %I', tbl, tbl); EXECUTE format( 'CREATE TRIGGER trg_db_tamper_%I AFTER INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION trg_fn_db_tamper_guard()', tbl, tbl ); END LOOP; END $$; -- P4: ledger entries are append-only (blocks UPDATE/DELETE even via authorized app flag) CREATE OR REPLACE FUNCTION trg_fn_ledger_entries_immutable() RETURNS TRIGGER AS $$ BEGIN RAISE EXCEPTION 'ledger_entries are append-only and cannot be modified or deleted'; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS trg_ledger_entries_immutable ON ledger_entries; CREATE TRIGGER trg_ledger_entries_immutable BEFORE UPDATE OR DELETE ON ledger_entries FOR EACH ROW EXECUTE FUNCTION trg_fn_ledger_entries_immutable(); -- P6 security: JWT invalidation version, session metadata, withdrawal 2FA, session limits DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'token_version' ) THEN ALTER TABLE users ADD COLUMN token_version INTEGER NOT NULL DEFAULT 1; END IF; END $$; DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'refresh_tokens' AND column_name = 'ip_address' ) THEN ALTER TABLE refresh_tokens ADD COLUMN ip_address VARCHAR(45); ALTER TABLE refresh_tokens ADD COLUMN user_agent VARCHAR(512); END IF; END $$; INSERT INTO system_settings (key, value) VALUES ('require_withdrawal_2fa', 'true'), ('max_concurrent_sessions', '10') ON CONFLICT (key) DO NOTHING; -- P8 security: soft-delete users DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'deleted_at' ) THEN ALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ; END IF; END $$; CREATE INDEX IF NOT EXISTS idx_users_deleted_at ON users(deleted_at) WHERE deleted_at IS NOT NULL; -- P9 security: file integrity monitoring + sybil auto-suspend CREATE TABLE IF NOT EXISTS file_integrity_snapshots ( root_key VARCHAR(64) NOT NULL, relative_path TEXT NOT NULL, content_sha256 CHAR(64) NOT NULL, size_bytes BIGINT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (root_key, relative_path) ); INSERT INTO system_settings (key, value) VALUES ('sybil_auto_suspend_accounts', 'true'), ('login_risk_auto_suspend_accounts', 'false'), ('login_risk_auto_suspend_threshold', '70'), ('encryption_key_rotated_at', ''), ('engine_audit_log_retention_days', '7') ON CONFLICT (key) DO NOTHING; INSERT INTO system_settings (key, value) VALUES ('candle_predict_retention_days', '30'), ('candle_predict_retention_keep_last', '5000') ON CONFLICT (key) DO NOTHING; -- Referral commissions on each validated prediction (stake-based) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_program_settings' AND column_name = 'prediction_commissions_enabled' ) THEN ALTER TABLE referral_program_settings ADD COLUMN prediction_commissions_enabled BOOLEAN NOT NULL DEFAULT TRUE; -- One-shot: switch primary mode to prediction for existing installs UPDATE referral_program_settings SET deposit_commissions_enabled = FALSE, withdrawal_commissions_enabled = FALSE, updated_at = NOW() WHERE id = 1; END IF; END $$; DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts' AND column_name = 'candle_predict_bet_id' ) THEN ALTER TABLE referral_commission_payouts ADD COLUMN candle_predict_bet_id UUID REFERENCES candle_predict_bets(id); END IF; END $$; DO $$ DECLARE r record; BEGIN -- Recreate commission_source check to allow 'prediction' (idempotent) IF NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conrelid = 'public.referral_commission_payouts'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%prediction%' AND pg_get_constraintdef(oid) LIKE '%commission_source%' ) THEN FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'public.referral_commission_payouts'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%commission_source%' LOOP EXECUTE format('ALTER TABLE referral_commission_payouts DROP CONSTRAINT %I', r.conname); END LOOP; ALTER TABLE referral_commission_payouts ADD CONSTRAINT referral_commission_payouts_commission_source_check CHECK (commission_source IN ('deposit', 'withdrawal', 'prediction')); END IF; END $$; CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_prediction_unique ON referral_commission_payouts (candle_predict_bet_id, beneficiary_user_id, level_number) WHERE commission_source = 'prediction' AND candle_predict_bet_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_referral_payouts_prediction_bet ON referral_commission_payouts (candle_predict_bet_id) WHERE candle_predict_bet_id IS NOT NULL; -- Share Cards: prediction result sharing (admin-configurable) CREATE TABLE IF NOT EXISTS share_card_settings ( id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT TRUE, allow_main_wallet BOOLEAN NOT NULL DEFAULT TRUE, allow_bonus_wallet BOOLEAN NOT NULL DEFAULT TRUE, allow_test_wallet BOOLEAN NOT NULL DEFAULT FALSE, allow_won BOOLEAN NOT NULL DEFAULT TRUE, allow_lost BOOLEAN NOT NULL DEFAULT TRUE, allow_refunded BOOLEAN NOT NULL DEFAULT TRUE, wallet_ops_enabled BOOLEAN NOT NULL DEFAULT TRUE, allow_deposit BOOLEAN NOT NULL DEFAULT TRUE, allow_withdrawal BOOLEAN NOT NULL DEFAULT TRUE, allow_transfer BOOLEAN NOT NULL DEFAULT TRUE, test_wallet_share_requires_real_deposit BOOLEAN NOT NULL DEFAULT TRUE, updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO share_card_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING; DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'share_card_settings' AND column_name = 'wallet_ops_enabled' ) THEN ALTER TABLE share_card_settings ADD COLUMN wallet_ops_enabled BOOLEAN NOT NULL DEFAULT TRUE, ADD COLUMN allow_deposit BOOLEAN NOT NULL DEFAULT TRUE, ADD COLUMN allow_withdrawal BOOLEAN NOT NULL DEFAULT TRUE, ADD COLUMN allow_transfer BOOLEAN NOT NULL DEFAULT TRUE; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'share_card_settings' AND column_name = 'test_wallet_share_requires_real_deposit' ) THEN ALTER TABLE share_card_settings ADD COLUMN test_wallet_share_requires_real_deposit BOOLEAN NOT NULL DEFAULT TRUE; END IF; END $$; -- Tamper trigger for share_card_settings (created after the table exists) DO $$ BEGIN EXECUTE format('DROP TRIGGER IF EXISTS trg_db_tamper_%I ON %I', 'share_card_settings', 'share_card_settings'); EXECUTE format( 'CREATE TRIGGER trg_db_tamper_%I AFTER INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION trg_fn_db_tamper_guard()', 'share_card_settings', 'share_card_settings' ); END $$; -- Candle Predict chart instrument branding (admin-editable, display-only) DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'instrument_symbol' ) THEN ALTER TABLE candle_predict_config ADD COLUMN instrument_symbol VARCHAR(16) NOT NULL DEFAULT 'FO', ADD COLUMN instrument_display_name VARCHAR(64) NOT NULL DEFAULT 'Full Option', ADD COLUMN instrument_quote_currency VARCHAR(16) NOT NULL DEFAULT 'USDT', ADD COLUMN instrument_price_digits SMALLINT NOT NULL DEFAULT 2 CHECK (instrument_price_digits >= 0 AND instrument_price_digits <= 8); END IF; END $$; -- Marketing Live Activity: synthetic personas + singleton settings (admin-configurable) CREATE TABLE IF NOT EXISTS marketing_personas ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), public_id VARCHAR(32) NOT NULL UNIQUE, is_active BOOLEAN NOT NULL DEFAULT TRUE, sort_order INT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_marketing_personas_active_sort ON marketing_personas (is_active, sort_order, public_id); CREATE TABLE IF NOT EXISTS marketing_live_activity_settings ( id INT PRIMARY KEY CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT TRUE, real_active_threshold INT NOT NULL DEFAULT 200 CHECK (real_active_threshold > 0), max_synthetic_entries INT NOT NULL DEFAULT 20 CHECK (max_synthetic_entries >= 0 AND max_synthetic_entries <= 100), display_active_target INT NOT NULL DEFAULT 250 CHECK (display_active_target > 0), display_active_spread INT NOT NULL DEFAULT 40 CHECK (display_active_spread >= 0 AND display_active_spread <= 500), active_window_minutes INT NOT NULL DEFAULT 15 CHECK (active_window_minutes > 0), feed_real_fetch INT NOT NULL DEFAULT 16 CHECK (feed_real_fetch > 0), client_refresh_seconds INT NOT NULL DEFAULT 30 CHECK (client_refresh_seconds >= 10 AND client_refresh_seconds <= 120), list_rotate_seconds INT NOT NULL DEFAULT 8 CHECK (list_rotate_seconds >= 5 AND list_rotate_seconds <= 60), cache_ttl_seconds INT NOT NULL DEFAULT 12 CHECK (cache_ttl_seconds > 0), max_synthetic_withdrawals INT NOT NULL DEFAULT 12 CHECK (max_synthetic_withdrawals >= 0 AND max_synthetic_withdrawals <= 100), synthetic_withdrawal_amounts NUMERIC(18,6)[] NOT NULL DEFAULT ARRAY[20,35,50,80,100,120,200,250,300,450,500,800]::NUMERIC(18,6)[], withdrawal_real_window_hours INT NOT NULL DEFAULT 48 CHECK (withdrawal_real_window_hours > 0), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); INSERT INTO marketing_live_activity_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING; -- V2: withdrawal feed plafond + amounts + lively counter spread (idempotent) DO $$ DECLARE r RECORD; BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' AND column_name = 'max_synthetic_withdrawals' ) THEN ALTER TABLE marketing_live_activity_settings ADD COLUMN max_synthetic_withdrawals INT NOT NULL DEFAULT 12 CHECK (max_synthetic_withdrawals >= 0 AND max_synthetic_withdrawals <= 100); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' AND column_name = 'synthetic_withdrawal_amounts' ) THEN ALTER TABLE marketing_live_activity_settings ADD COLUMN synthetic_withdrawal_amounts NUMERIC(18,6)[] NOT NULL DEFAULT ARRAY[20,35,50,80,100,120,200,250,300,450,500,800]::NUMERIC(18,6)[]; ELSIF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' AND column_name = 'synthetic_withdrawal_amounts' AND udt_name = '_int4' ) THEN -- Allow decimal fictive amounts (was INT[]). ALTER TABLE marketing_live_activity_settings ALTER COLUMN synthetic_withdrawal_amounts TYPE NUMERIC(18,6)[] USING synthetic_withdrawal_amounts::NUMERIC(18,6)[]; END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' AND column_name = 'display_active_spread' ) THEN ALTER TABLE marketing_live_activity_settings ADD COLUMN display_active_spread INT NOT NULL DEFAULT 40 CHECK (display_active_spread >= 0 AND display_active_spread <= 500); END IF; IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'marketing_live_activity_settings' AND column_name = 'withdrawal_real_window_hours' ) THEN ALTER TABLE marketing_live_activity_settings ADD COLUMN withdrawal_real_window_hours INT NOT NULL DEFAULT 48; END IF; -- Drop ANY check on this column (PG truncates long auto names like -- marketing_live_activity_sett_withdrawal_real_window_hours_check that still -- enforce <= 720). Then ensure a short positive-only constraint. FOR r IN SELECT c.conname FROM pg_constraint c JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey) WHERE c.conrelid = 'public.marketing_live_activity_settings'::regclass AND c.contype = 'c' AND a.attname = 'withdrawal_real_window_hours' LOOP EXECUTE format( 'ALTER TABLE marketing_live_activity_settings DROP CONSTRAINT %I', r.conname ); END LOOP; IF NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conrelid = 'public.marketing_live_activity_settings'::regclass AND conname = 'mkt_wd_real_window_hours_pos' ) THEN ALTER TABLE marketing_live_activity_settings ADD CONSTRAINT mkt_wd_real_window_hours_pos CHECK (withdrawal_real_window_hours > 0); END IF; END $$; INSERT INTO marketing_personas (public_id, is_active, sort_order) VALUES ('7a***k2', TRUE, 1), ('9c***m1', TRUE, 2), ('3f***p8', TRUE, 3), ('b2***q4', TRUE, 4), ('e8***t6', TRUE, 5), ('1d***w9', TRUE, 6), ('5h***n3', TRUE, 7), ('c4***r7', TRUE, 8), ('8j***v5', TRUE, 9), ('2m***x0', TRUE, 10), ('6p***y1', TRUE, 11), ('0s***z8', TRUE, 12), ('4n***a3', TRUE, 13), ('d7***b5', TRUE, 14), ('f1***c9', TRUE, 15), ('a9***d2', TRUE, 16), ('g3***e4', TRUE, 17), ('h6***f7', TRUE, 18), ('i2***g1', TRUE, 19), ('j8***h6', TRUE, 20) ON CONFLICT (public_id) DO NOTHING; -- --------------------------------------------------------------------------- -- Mobile app releases (Android APK distribution) -- --------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS mobile_app_update_settings ( id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), min_supported_version_code INT NOT NULL DEFAULT 1 CHECK (min_supported_version_code >= 1), check_interval_seconds INT NOT NULL DEFAULT 21600 CHECK (check_interval_seconds >= 60 AND check_interval_seconds <= 604800), expected_package_name TEXT NOT NULL DEFAULT 'com.prediqo.mobile', updated_at TIMESTAMPTZ DEFAULT NOW() ); INSERT INTO mobile_app_update_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING; CREATE TABLE IF NOT EXISTS mobile_app_releases ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), platform TEXT NOT NULL DEFAULT 'android' CHECK (platform IN ('android', 'ios')), channel TEXT NOT NULL DEFAULT 'production' CHECK (channel IN ('production', 'beta', 'internal')), version_name TEXT NOT NULL, version_code INT NOT NULL CHECK (version_code >= 1), package_name TEXT, previous_version_name TEXT, whats_new TEXT NOT NULL DEFAULT '', bug_fixes TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'pending_validation', 'published', 'suspended', 'retired')), update_policy TEXT NOT NULL DEFAULT 'optional' CHECK (update_policy IN ('optional', 'recommended', 'mandatory')), rollout_percent INT NOT NULL DEFAULT 100 CHECK (rollout_percent >= 0 AND rollout_percent <= 100), storage_key TEXT, file_size_bytes BIGINT, sha256 TEXT, signing_cert_sha256 TEXT, published_at TIMESTAMPTZ, created_by UUID REFERENCES users(id) ON DELETE SET NULL, download_count BIGINT NOT NULL DEFAULT 0, download_fail_count BIGINT NOT NULL DEFAULT 0, install_confirm_count BIGINT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE (platform, channel, version_code) ); CREATE INDEX IF NOT EXISTS idx_mobile_app_releases_lookup ON mobile_app_releases (platform, channel, status, version_code DESC); CREATE TABLE IF NOT EXISTS mobile_app_release_events ( id BIGSERIAL PRIMARY KEY, release_id UUID REFERENCES mobile_app_releases(id) ON DELETE SET NULL, event_type TEXT NOT NULL CHECK (event_type IN ('check', 'download_start', 'download_ok', 'download_fail', 'install_confirm')), platform TEXT NOT NULL DEFAULT 'android', channel TEXT NOT NULL DEFAULT 'production', client_version_code INT, device_id_hash TEXT, user_id UUID REFERENCES users(id) ON DELETE SET NULL, meta JSONB NOT NULL DEFAULT '{}'::jsonb, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_mobile_app_release_events_release ON mobile_app_release_events (release_id, event_type, created_at DESC); CREATE INDEX IF NOT EXISTS idx_mobile_app_release_events_created ON mobile_app_release_events (created_at DESC);