diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 3278fa55..9264c0e9 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -3,466 +3,659 @@ -- Roles CREATE TABLE IF NOT EXISTS roles ( - id SERIAL PRIMARY KEY, - name VARCHAR(50) UNIQUE NOT NULL, - description TEXT + 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; +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 + 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; +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) + 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 = '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 = '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; +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() + 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; +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) + 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); +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) + 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); +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; +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 + 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); +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' - )); +DROP CONSTRAINT IF EXISTS fund_operation_requests_operation_type_check; -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' - )); +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 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); +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() + 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 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() + 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 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) + 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); +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() + 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); +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() + 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); +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) + 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; +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) + 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); +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) + 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; +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) + 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); +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() + 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); +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() + 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 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); +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() + 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); +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() + 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_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 + 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); +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) + 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() + 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); +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() + 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); +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); +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() + 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; +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 $$ @@ -495,88 +688,134 @@ 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() + 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); +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() + 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); +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() + 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); +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; +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 ('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 ( + '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; +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() + 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 @@ -591,41 +830,70 @@ BEGIN END $$; UPDATE games -SET implementation_key = 'candle-predict' -WHERE slug = 'candle-predict' AND implementation_key IS NULL; +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; +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() + 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); +CREATE INDEX IF NOT EXISTS idx_advertisements_placement ON advertisements (placement); -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; +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.', + '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'; @@ -660,138 +928,267 @@ CREATE TABLE IF NOT EXISTS candle_predict_config ( updated_at TIMESTAMPTZ DEFAULT NOW() ); -INSERT INTO candle_predict_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING; +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 + 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 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) + 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 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() + 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); +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 + +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 + +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() + 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 $$ @@ -849,20 +1246,26 @@ BEGIN 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 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() + 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 $$ @@ -912,113 +1315,160 @@ BEGIN 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 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() + 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); +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() + 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 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() + 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); +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); +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); +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() + 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() + 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; +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() + 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); +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); +ADD COLUMN IF NOT EXISTS requested_by UUID REFERENCES users (id); -- Referral program & bonus accounts DO $$ @@ -1055,76 +1505,103 @@ BEGIN 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 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() + 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; +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() + 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; +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) + 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 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() + 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; +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'; +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 +SET + commission_wallet_type_id = wt.id FROM wallet_types wt -WHERE referral_program_settings.id = 1 AND wt.code = 'USDT_TRC20'; +WHERE + referral_program_settings.id = 1 + AND wt.code = 'USDT_TRC20'; -- Extend exchange_funding for cold ↔ hot treasury moves (manual confirm workflow) DO $$ @@ -1149,19 +1626,47 @@ BEGIN 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); +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'); +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 $$ @@ -1198,65 +1703,83 @@ 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() + 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_user_admin_stats_main_balance ON user_admin_stats (main_balance_raw); -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); +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) + 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); +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 @@ -1272,21 +1795,28 @@ 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() + 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; +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 $$ @@ -1310,33 +1840,41 @@ BEGIN 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() + 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'; +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() + 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; +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, @@ -1364,13 +1902,13 @@ CREATE TABLE IF NOT EXISTS solo_encouragement_grants ( 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; +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 @@ -1388,7 +1926,7 @@ BEGIN ALTER TABLE ledger_accounts ADD CONSTRAINT ledger_accounts_account_kind_check CHECK (account_kind IN ('main', 'bonus', 'test')); - FOR r IN +FOR r IN SELECT conname FROM pg_constraint WHERE conrelid = 'candle_predict_bets'::regclass @@ -1396,11 +1934,15 @@ BEGIN 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 +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 @@ -1408,23 +1950,38 @@ BEGIN 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 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; +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 $$ @@ -1476,23 +2033,31 @@ BEGIN 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_format_check; -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')); +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); + +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 @@ -1537,8 +2102,14 @@ SELECT 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 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 @@ -1549,8 +2120,7 @@ SELECT 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 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 @@ -1559,8 +2129,7 @@ SELECT FROM candle_predict_bets GROUP BY 1; -CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_hourly_bets_pk - ON analytics_hourly_bets(hour_ts); +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 $$ @@ -1573,7 +2142,9 @@ BEGIN 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 IF; + END $$; CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_transactions AS @@ -1634,8 +2205,12 @@ SELECT 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 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 @@ -1647,8 +2222,7 @@ SELECT 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 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 @@ -1659,8 +2233,7 @@ SELECT 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 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 @@ -1672,8 +2245,7 @@ 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 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 ( @@ -1686,8 +2258,7 @@ SELECT day, user_id FROM ( ) 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); +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 $$ @@ -1697,9 +2268,15 @@ BEGIN 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; + +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) @@ -1724,20 +2301,23 @@ BEGIN 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() + 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() + 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). @@ -1781,12 +2361,18 @@ BEGIN 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; +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 @@ -1802,21 +2388,33 @@ BEGIN END IF; END $$; -UPDATE candle_predict_bets SET prediction_mode = 'single' WHERE prediction_mode IS NULL OR prediction_mode = ''; +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; +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_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 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'; +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 @@ -1833,6 +2431,7 @@ BEGIN 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 @@ -1908,11 +2507,12 @@ BEGIN END IF; END $$; -CREATE INDEX IF NOT EXISTS idx_referral_payouts_pending - ON referral_commission_payouts(eligible_at) - WHERE status = 'pending'; +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, @@ -1923,8 +2523,7 @@ 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); +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 $$ @@ -1934,63 +2533,86 @@ BEGIN 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; +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_detection_enabled' +) THEN +ALTER TABLE referral_program_settings +ADD COLUMN sybil_detection_enabled BOOLEAN NOT NULL DEFAULT TRUE; - 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; +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_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); - 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 +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; + +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 $$ @@ -2007,11 +2629,17 @@ 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'; +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 $$ @@ -2023,32 +2651,41 @@ BEGIN ) 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 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() + 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); +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 @@ -2056,16 +2693,29 @@ BEGIN 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 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); +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 $$ @@ -2077,19 +2727,25 @@ BEGIN ) 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; +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 @@ -2132,59 +2788,106 @@ BEGIN 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_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 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_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); +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)) + 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 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) + 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 $$ @@ -2203,62 +2906,82 @@ BEGIN 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; +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; +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() + 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() + 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 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) + 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; +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) @@ -2280,9 +3003,11 @@ CREATE TABLE IF NOT EXISTS db_tamper_events ( 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 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 $$ @@ -2486,35 +3211,46 @@ BEGIN 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() + 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); +CREATE INDEX IF NOT EXISTS idx_totp_recovery_user ON user_totp_recovery_codes (user_id); -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 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) + 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); +CREATE INDEX IF NOT EXISTS idx_login_fingerprints_user ON user_login_fingerprints (user_id); DO $$ BEGIN @@ -2523,22 +3259,27 @@ BEGIN 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 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() + 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; +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 @@ -2580,6 +3321,7 @@ 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(); @@ -2606,10 +3348,16 @@ BEGIN END IF; END $$; -INSERT INTO system_settings (key, value) VALUES - ('require_withdrawal_2fa', 'true'), - ('max_concurrent_sessions', '10') -ON CONFLICT (key) DO NOTHING; +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 $$ @@ -2622,30 +3370,53 @@ BEGIN END IF; END $$; -CREATE INDEX IF NOT EXISTS idx_users_deleted_at ON users(deleted_at) WHERE deleted_at IS NOT NULL; +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) + 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 ( + '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; +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 $$ @@ -2703,35 +3474,40 @@ BEGIN 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 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; +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() + 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; +INSERT INTO + share_card_settings (id) +VALUES (1) ON CONFLICT (id) DO NOTHING; DO $$ BEGIN @@ -2785,19 +3561,21 @@ BEGIN 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() + 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 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), @@ -2817,9 +3595,9 @@ CREATE TABLE IF NOT EXISTS marketing_live_activity_settings ( updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -INSERT INTO marketing_live_activity_settings (id) -VALUES (1) -ON CONFLICT (id) DO NOTHING; +INSERT INTO + marketing_live_activity_settings (id) +VALUES (1) ON CONFLICT (id) DO NOTHING; -- V2: withdrawal feed plafond + amounts + lively counter spread (idempotent) DO $$ @@ -2899,77 +3677,116 @@ BEGIN 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; +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() + 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; +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) + 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 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, @@ -2985,10 +3802,13 @@ CREATE TABLE IF NOT EXISTS mobile_app_release_events ( 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); +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); -- Max consecutive same-direction candles in auto/random (no real-money) generation. DO $$ @@ -3001,6 +3821,7 @@ BEGIN ALTER TABLE candle_predict_config ADD COLUMN max_consecutive_same_direction INTEGER NOT NULL DEFAULT 5 CHECK (max_consecutive_same_direction >= 0 AND max_consecutive_same_direction <= 50); - END IF; -END -$$; + +END IF; + +END $$; \ No newline at end of file diff --git a/prediqo_web/src/features/landing/LandingPage.tsx b/prediqo_web/src/features/landing/LandingPage.tsx index 8f5f88cf..575892e3 100644 --- a/prediqo_web/src/features/landing/LandingPage.tsx +++ b/prediqo_web/src/features/landing/LandingPage.tsx @@ -154,23 +154,25 @@ export function LandingPage() { {t('landing.live.subtitle')}

- {typeof activePlayers === 'number' && activePlayers > 0 && ( - - - {t('landing.live.subtitleWithCount', { count: activePlayers })} - - )}
- +
+ {typeof activePlayers === 'number' && activePlayers > 0 && ( + + + {t('landing.live.subtitleWithCount', { count: activePlayers })} + + )} + +