Fix fresh-DB migration order for candle_predict_auto_settings, fail loudly on migrate errors, honor DATABASE_URL from .env, add Docker DNS resolver for nginx upstreams, and document VPS deploy steps. Co-authored-by: Cursor <cursoragent@cursor.com>
2096 lines
85 KiB
PL/PgSQL
2096 lines
85 KiB
PL/PgSQL
-- Crypto Wallet Platform - PostgreSQL Schema
|
|
-- Ledger is source of truth; blockchain confirms only.
|
|
|
|
-- Roles
|
|
CREATE TABLE IF NOT EXISTS roles (
|
|
id SERIAL PRIMARY KEY,
|
|
name VARCHAR(50) UNIQUE NOT NULL,
|
|
description TEXT
|
|
);
|
|
|
|
INSERT INTO roles (name, description) VALUES
|
|
('user', 'Regular platform user'),
|
|
('moderator', 'Moderator with limited admin'),
|
|
('admin', 'Full platform administrator')
|
|
ON CONFLICT (name) DO NOTHING;
|
|
|
|
-- Users (sensitive fields encrypted at application layer)
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
first_name VARCHAR(100),
|
|
middle_name VARCHAR(100),
|
|
last_name VARCHAR(100),
|
|
date_of_birth DATE,
|
|
email_encrypted VARCHAR(255),
|
|
email_hash VARCHAR(64) UNIQUE NOT NULL,
|
|
phone_encrypted VARCHAR(255),
|
|
phone_hash VARCHAR(64),
|
|
password_hash VARCHAR(255) NOT NULL,
|
|
role_id INTEGER NOT NULL REFERENCES roles(id) DEFAULT 1,
|
|
email_verified BOOLEAN DEFAULT FALSE,
|
|
phone_verified BOOLEAN DEFAULT FALSE,
|
|
totp_secret_encrypted VARCHAR(512),
|
|
totp_enabled BOOLEAN DEFAULT FALSE,
|
|
is_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
is_account_non_expired BOOLEAN NOT NULL DEFAULT TRUE,
|
|
is_account_non_locked BOOLEAN NOT NULL DEFAULT TRUE,
|
|
is_credentials_non_expired BOOLEAN NOT NULL DEFAULT TRUE,
|
|
withdrawals_suspended BOOLEAN NOT NULL DEFAULT FALSE,
|
|
under_surveillance BOOLEAN NOT NULL DEFAULT FALSE,
|
|
security_suspended_at TIMESTAMPTZ,
|
|
security_reason_encrypted TEXT,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_users_email_hash ON users(email_hash);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone_hash_unique ON users(phone_hash) WHERE phone_hash IS NOT NULL;
|
|
|
|
-- Refresh tokens
|
|
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
token_hash VARCHAR(255) NOT NULL,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires ON refresh_tokens(expires_at);
|
|
|
|
-- Wallet types (USDT TRC20 only — platform stablecoin for deposits and predictions)
|
|
CREATE TABLE IF NOT EXISTS wallet_types (
|
|
id SERIAL PRIMARY KEY,
|
|
code VARCHAR(32) UNIQUE NOT NULL,
|
|
name VARCHAR(100) NOT NULL,
|
|
network VARCHAR(50) NOT NULL,
|
|
decimals INTEGER NOT NULL DEFAULT 6,
|
|
contract_address VARCHAR(255)
|
|
);
|
|
|
|
INSERT INTO wallet_types (code, name, network, decimals, contract_address) VALUES
|
|
('USDT_TRC20', 'USDT (TRC20)', 'TRON', 6, 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t')
|
|
ON CONFLICT (code) DO NOTHING;
|
|
|
|
-- User deposit addresses (derived from HD wallet; only public address stored)
|
|
CREATE TABLE IF NOT EXISTS user_wallets (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
address VARCHAR(255) NOT NULL,
|
|
derivation_index INTEGER NOT NULL,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
UNIQUE(user_id, wallet_type_id)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_user_wallets_user ON user_wallets(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_user_wallets_address ON user_wallets(address);
|
|
CREATE INDEX IF NOT EXISTS idx_user_wallets_type ON user_wallets(wallet_type_id);
|
|
|
|
-- Hot wallet addresses (platform signs withdrawals from these)
|
|
CREATE TABLE IF NOT EXISTS hot_wallets (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
address VARCHAR(255) NOT NULL,
|
|
encrypted_private_key TEXT NOT NULL,
|
|
derivation_index INTEGER,
|
|
is_active BOOLEAN DEFAULT TRUE,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_hot_wallets_type ON hot_wallets(wallet_type_id);
|
|
|
|
-- Ledger: canonical source of truth for balances
|
|
CREATE TABLE IF NOT EXISTS ledger_accounts (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
available_balance BIGINT NOT NULL DEFAULT 0,
|
|
locked_balance BIGINT NOT NULL DEFAULT 0,
|
|
account_kind VARCHAR(16) NOT NULL DEFAULT 'main' CHECK (account_kind IN ('main', 'bonus', 'test')),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_accounts_user_wallet_kind
|
|
ON ledger_accounts(user_id, wallet_type_id, account_kind);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_user ON ledger_accounts(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_wallet_type ON ledger_accounts(wallet_type_id);
|
|
|
|
-- Ledger entries (double-entry style for audit)
|
|
CREATE TABLE IF NOT EXISTS ledger_entries (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
account_id UUID NOT NULL REFERENCES ledger_accounts(id),
|
|
type VARCHAR(32) NOT NULL,
|
|
amount BIGINT NOT NULL,
|
|
balance_after BIGINT NOT NULL,
|
|
reference_type VARCHAR(50),
|
|
reference_id UUID,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_entries_account ON ledger_entries(account_id);
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_entries_created ON ledger_entries(created_at);
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_entries_reference ON ledger_entries(reference_type, reference_id);
|
|
|
|
-- Transactions (deposits, withdrawals, transfers)
|
|
CREATE TABLE IF NOT EXISTS transactions (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id),
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
type VARCHAR(32) NOT NULL,
|
|
amount BIGINT NOT NULL,
|
|
fee BIGINT DEFAULT 0,
|
|
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
|
blockchain_tx_id VARCHAR(255),
|
|
from_address VARCHAR(255),
|
|
to_address VARCHAR(255),
|
|
confirmations INTEGER DEFAULT 0,
|
|
required_confirmations INTEGER,
|
|
metadata JSONB,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_transactions_user ON transactions(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_transactions_status ON transactions(status);
|
|
CREATE INDEX IF NOT EXISTS idx_transactions_blockchain_tx ON transactions(blockchain_tx_id);
|
|
CREATE INDEX IF NOT EXISTS idx_transactions_created ON transactions(created_at);
|
|
CREATE INDEX IF NOT EXISTS idx_transactions_type ON transactions(type);
|
|
|
|
-- Withdrawal locks (amount locked while withdrawal is processing)
|
|
CREATE TABLE IF NOT EXISTS withdrawal_locks (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id),
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
transaction_id UUID REFERENCES transactions(id),
|
|
amount BIGINT NOT NULL,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
expires_at TIMESTAMPTZ
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_withdrawal_locks_user ON withdrawal_locks(user_id);
|
|
|
|
-- Deposit monitoring: track scanned blocks to avoid re-processing
|
|
CREATE TABLE IF NOT EXISTS deposit_scanner_state (
|
|
id SERIAL PRIMARY KEY,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
last_block BIGINT NOT NULL DEFAULT 0,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
|
UNIQUE(wallet_type_id)
|
|
);
|
|
|
|
-- Audit log for sensitive actions
|
|
CREATE TABLE IF NOT EXISTS audit_logs (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID REFERENCES users(id),
|
|
action VARCHAR(100) NOT NULL,
|
|
resource_type VARCHAR(50),
|
|
resource_id VARCHAR(255),
|
|
ip_address VARCHAR(45),
|
|
user_agent TEXT,
|
|
metadata JSONB,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_audit_logs_user ON audit_logs(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_audit_logs_action ON audit_logs(action);
|
|
CREATE INDEX IF NOT EXISTS idx_audit_logs_created ON audit_logs(created_at);
|
|
|
|
-- Exchange funding records (platform moves to/from exchange)
|
|
CREATE TABLE IF NOT EXISTS exchange_funding (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
direction VARCHAR(20) NOT NULL,
|
|
amount BIGINT NOT NULL,
|
|
blockchain_tx_id VARCHAR(255),
|
|
exchange_name VARCHAR(50),
|
|
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
|
approved_by UUID REFERENCES users(id),
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_exchange_funding_status ON exchange_funding(status);
|
|
|
|
-- System settings (admin-configurable: password policy, token expiry)
|
|
CREATE TABLE IF NOT EXISTS system_settings (
|
|
key VARCHAR(100) PRIMARY KEY,
|
|
value TEXT NOT NULL,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
INSERT INTO system_settings (key, value) VALUES
|
|
('password_min_length', '8'),
|
|
('password_require_uppercase', 'true'),
|
|
('password_require_lowercase', 'true'),
|
|
('password_require_number', 'true'),
|
|
('password_require_special', 'true'),
|
|
('access_token_expiry', '15m'),
|
|
('refresh_token_expiry', '7d')
|
|
ON CONFLICT (key) DO NOTHING;
|
|
|
|
-- Migration: add account status columns to users (for existing DBs)
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_enabled') THEN
|
|
ALTER TABLE users ADD COLUMN is_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_account_non_expired') THEN
|
|
ALTER TABLE users ADD COLUMN is_account_non_expired BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_account_non_locked') THEN
|
|
ALTER TABLE users ADD COLUMN is_account_non_locked BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'is_credentials_non_expired') THEN
|
|
ALTER TABLE users ADD COLUMN is_credentials_non_expired BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'first_name') THEN
|
|
ALTER TABLE users ADD COLUMN first_name VARCHAR(100);
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'middle_name') THEN
|
|
ALTER TABLE users ADD COLUMN middle_name VARCHAR(100);
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'last_name') THEN
|
|
ALTER TABLE users ADD COLUMN last_name VARCHAR(100);
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'date_of_birth') THEN
|
|
ALTER TABLE users ADD COLUMN date_of_birth DATE;
|
|
END IF;
|
|
END $$;
|
|
|
|
-- Email verification tokens (single-use, hashed at rest)
|
|
CREATE TABLE IF NOT EXISTS email_verification_tokens (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
token_hash VARCHAR(64) NOT NULL,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
used_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_user ON email_verification_tokens(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_hash ON email_verification_tokens(token_hash);
|
|
CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_expires ON email_verification_tokens(expires_at);
|
|
|
|
-- Password reset tokens (single-use, hashed at rest)
|
|
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
token_hash VARCHAR(64) NOT NULL,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
used_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user ON password_reset_tokens(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_hash ON password_reset_tokens(token_hash);
|
|
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_expires ON password_reset_tokens(expires_at);
|
|
|
|
-- Countries catalog (synced from REST Countries API; admin can block registration)
|
|
CREATE TABLE IF NOT EXISTS countries (
|
|
code CHAR(2) PRIMARY KEY,
|
|
name VARCHAR(120) NOT NULL,
|
|
registration_allowed BOOLEAN NOT NULL DEFAULT TRUE,
|
|
synced_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_countries_registration ON countries(registration_allowed);
|
|
|
|
INSERT INTO system_settings (key, value) VALUES
|
|
('require_email_verification_for_login', 'true')
|
|
ON CONFLICT (key) DO NOTHING;
|
|
|
|
-- Runtime ops defaults (env-backed until admin overrides via Settings UI)
|
|
INSERT INTO system_settings (key, value) VALUES
|
|
('allow_withdrawals', 'false'),
|
|
('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;
|
|
|
|
-- Games catalog (prediction games available on the platform)
|
|
CREATE TABLE IF NOT EXISTS games (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
slug VARCHAR(80) UNIQUE NOT NULL,
|
|
title VARCHAR(150) NOT NULL,
|
|
description TEXT,
|
|
category VARCHAR(50) NOT NULL DEFAULT 'prediction',
|
|
thumbnail_url TEXT,
|
|
accent_color VARCHAR(16) DEFAULT '#D6B25E',
|
|
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
is_featured BOOLEAN NOT NULL DEFAULT FALSE,
|
|
implementation_key VARCHAR(64),
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
-- Existing databases: add implementation_key before indexes/inserts that reference it
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'games' AND column_name = 'implementation_key'
|
|
) THEN
|
|
ALTER TABLE games ADD COLUMN implementation_key VARCHAR(64);
|
|
END IF;
|
|
END $$;
|
|
|
|
UPDATE games
|
|
SET implementation_key = 'candle-predict'
|
|
WHERE slug = 'candle-predict' AND implementation_key IS NULL;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_games_status ON games(status);
|
|
CREATE INDEX IF NOT EXISTS idx_games_sort ON games(sort_order);
|
|
CREATE INDEX IF NOT EXISTS idx_games_featured ON games(is_featured);
|
|
CREATE INDEX IF NOT EXISTS idx_games_implementation ON games(implementation_key)
|
|
WHERE implementation_key IS NOT NULL;
|
|
|
|
-- Dynamic advertisements / promotions (home page and placements)
|
|
CREATE TABLE IF NOT EXISTS advertisements (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
placement VARCHAR(50) NOT NULL DEFAULT 'home_hero',
|
|
title VARCHAR(200) NOT NULL,
|
|
subtitle TEXT,
|
|
cta_label VARCHAR(80),
|
|
link_url TEXT,
|
|
image_url TEXT,
|
|
background_gradient TEXT,
|
|
accent_color VARCHAR(16) DEFAULT '#7C5CFF',
|
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
starts_at TIMESTAMPTZ,
|
|
ends_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_advertisements_placement ON advertisements(placement);
|
|
CREATE INDEX IF NOT EXISTS idx_advertisements_active ON advertisements(is_active);
|
|
CREATE INDEX IF NOT EXISTS idx_advertisements_sort ON advertisements(sort_order);
|
|
|
|
INSERT INTO games (slug, title, description, category, accent_color, status, sort_order, is_featured, implementation_key) VALUES
|
|
('candle-predict', 'Candle Predict', 'Predict Short (bearish) or Long (bullish) on the next synthetic candle. The minority stake pool wins when pools differ enough.', 'prediction', '#D6B25E', 'active', 1, TRUE, 'candle-predict')
|
|
ON CONFLICT (slug) DO NOTHING;
|
|
|
|
-- Remove placeholder games from existing databases (keep only Candle Predict)
|
|
DELETE FROM games WHERE slug <> 'candle-predict';
|
|
|
|
-- Candle Predict game configuration (single row)
|
|
CREATE TABLE IF NOT EXISTS candle_predict_config (
|
|
id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
|
interval_minutes INTEGER NOT NULL DEFAULT 1,
|
|
stake_amounts JSONB NOT NULL DEFAULT '[1,5,10,20,50,100,1000]'::jsonb,
|
|
min_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 0.01,
|
|
max_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 1000,
|
|
pool_winner_rule VARCHAR(16) NOT NULL DEFAULT 'minority',
|
|
allowed_intervals JSONB NOT NULL DEFAULT '[1,3,5,10]'::jsonb,
|
|
prediction_window_seconds INTEGER NOT NULL DEFAULT 15,
|
|
tie_tolerance_percent NUMERIC(5,2) NOT NULL DEFAULT 2.00,
|
|
tie_tolerance_max_percent NUMERIC(5,2) NOT NULL DEFAULT 95.00,
|
|
tie_tolerance_min_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
tie_tolerance_max_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
base_price NUMERIC(18,6) NOT NULL DEFAULT 100.000000,
|
|
payout_multiplier NUMERIC(6,3) NOT NULL DEFAULT 1.900,
|
|
pool_multiplier NUMERIC(6,3) NOT NULL DEFAULT 1.900,
|
|
wallet_type_code VARCHAR(32) NOT NULL DEFAULT 'USDT_TRC20',
|
|
auto_modes JSONB NOT NULL DEFAULT '["each_round","interval"]'::jsonb,
|
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
INSERT INTO candle_predict_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
|
|
|
|
CREATE TABLE IF NOT EXISTS candle_predict_rounds (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
candle_open_ms BIGINT NOT NULL,
|
|
interval_minutes INTEGER NOT NULL,
|
|
status VARCHAR(20) NOT NULL DEFAULT 'betting',
|
|
short_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0,
|
|
long_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0,
|
|
open_price NUMERIC(24,8),
|
|
high_price NUMERIC(24,8),
|
|
low_price NUMERIC(24,8),
|
|
close_price NUMERIC(24,8),
|
|
outcome VARCHAR(20),
|
|
neutral_color VARCHAR(10),
|
|
total_bets INTEGER NOT NULL DEFAULT 0,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
settled_at TIMESTAMPTZ
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_candle_rounds_status ON candle_predict_rounds(status);
|
|
CREATE INDEX IF NOT EXISTS idx_candle_rounds_open ON candle_predict_rounds(candle_open_ms);
|
|
|
|
CREATE TABLE IF NOT EXISTS candle_predict_bets (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
round_id UUID NOT NULL REFERENCES candle_predict_rounds(id) ON DELETE CASCADE,
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
direction VARCHAR(10) NOT NULL CHECK (direction IN ('short', 'long')),
|
|
stake_raw BIGINT NOT NULL,
|
|
stake_display NUMERIC(18,6) NOT NULL,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
|
interval_minutes INTEGER NOT NULL DEFAULT 1,
|
|
payout_raw BIGINT NOT NULL DEFAULT 0,
|
|
is_auto BOOLEAN NOT NULL DEFAULT FALSE,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
UNIQUE (round_id, user_id)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_candle_bets_user ON candle_predict_bets(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_candle_bets_round ON candle_predict_bets(round_id);
|
|
|
|
CREATE TABLE IF NOT EXISTS candle_predict_candles (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
candle_open_ms BIGINT NOT NULL,
|
|
interval_minutes INTEGER NOT NULL DEFAULT 1,
|
|
open_price NUMERIC(24,8) NOT NULL,
|
|
high_price NUMERIC(24,8) NOT NULL,
|
|
low_price NUMERIC(24,8) NOT NULL,
|
|
close_price NUMERIC(24,8) NOT NULL,
|
|
color_hint VARCHAR(10) NOT NULL DEFAULT 'green',
|
|
outcome VARCHAR(20) NOT NULL,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_candle_predict_candles_open ON candle_predict_candles(candle_open_ms);
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'tie_tolerance_percent') THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_percent NUMERIC(5,2) NOT NULL DEFAULT 2.00;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'base_price') THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN base_price NUMERIC(18,6) NOT NULL DEFAULT 100.000000;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'min_stake_amount') THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN min_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 0.01;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'max_stake_amount') THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN max_stake_amount NUMERIC(18,6) NOT NULL DEFAULT 1000;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_config' AND column_name = 'pool_winner_rule') THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN pool_winner_rule VARCHAR(16) NOT NULL DEFAULT 'minority';
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'short_pool_display') THEN
|
|
ALTER TABLE candle_predict_rounds ADD COLUMN short_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'long_pool_display') THEN
|
|
ALTER TABLE candle_predict_rounds ADD COLUMN long_pool_display NUMERIC(18,6) NOT NULL DEFAULT 0;
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'outcome') THEN
|
|
ALTER TABLE candle_predict_rounds ADD COLUMN outcome VARCHAR(20);
|
|
END IF;
|
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_rounds' AND column_name = 'neutral_color') THEN
|
|
ALTER TABLE candle_predict_rounds ADD COLUMN neutral_color VARCHAR(10);
|
|
END IF;
|
|
-- Legacy columns from Binance-based version (removed in synthetic engine)
|
|
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_rounds' AND column_name = 'symbol') THEN
|
|
ALTER TABLE candle_predict_rounds DROP COLUMN symbol;
|
|
END IF;
|
|
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_rounds' AND column_name = 'result') THEN
|
|
ALTER TABLE candle_predict_rounds DROP COLUMN result;
|
|
END IF;
|
|
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'symbol') THEN
|
|
ALTER TABLE candle_predict_config DROP COLUMN symbol;
|
|
END IF;
|
|
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'long_body_min_ratio') THEN
|
|
ALTER TABLE candle_predict_config DROP COLUMN long_body_min_ratio;
|
|
END IF;
|
|
UPDATE games SET description = 'Predict Short (bearish) or Long (bullish) on the next synthetic candle. The minority stake pool wins when pools differ enough.' WHERE slug = 'candle-predict';
|
|
-- Legacy Binance defaults (5m / 15s window) made betting nearly invisible; move to playable defaults once.
|
|
UPDATE candle_predict_config
|
|
SET interval_minutes = 1,
|
|
prediction_window_seconds = 45
|
|
WHERE id = 1
|
|
AND interval_minutes = 5
|
|
AND prediction_window_seconds = 15;
|
|
UPDATE candle_predict_config
|
|
SET prediction_window_seconds = 45
|
|
WHERE id = 1
|
|
AND interval_minutes = 1
|
|
AND prediction_window_seconds >= 60;
|
|
END $$;
|
|
|
|
-- Multi-interval Candle Predict (configurable periods, separate rounds/candles per interval)
|
|
CREATE TABLE IF NOT EXISTS candle_predict_intervals (
|
|
id SERIAL PRIMARY KEY,
|
|
interval_minutes INTEGER NOT NULL UNIQUE,
|
|
label VARCHAR(64) NOT NULL,
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
is_default BOOLEAN NOT NULL DEFAULT FALSE,
|
|
prediction_window_seconds INTEGER,
|
|
tie_tolerance_percent NUMERIC(5,2),
|
|
tie_tolerance_max_percent NUMERIC(5,2),
|
|
tie_tolerance_min_enabled BOOLEAN,
|
|
tie_tolerance_max_enabled BOOLEAN,
|
|
payout_multiplier NUMERIC(6,3),
|
|
pool_multiplier NUMERIC(6,3),
|
|
base_price NUMERIC(18,6),
|
|
chart_candle_limit INTEGER NOT NULL DEFAULT 120,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
DO $$
|
|
DECLARE
|
|
mins INTEGER;
|
|
ord INTEGER := 0;
|
|
BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM candle_predict_intervals LIMIT 1) THEN
|
|
FOR mins IN SELECT unnest(ARRAY[1, 3, 5, 10, 15]) AS m LOOP
|
|
ord := ord + 1;
|
|
INSERT INTO candle_predict_intervals (interval_minutes, label, sort_order, is_default, is_active)
|
|
VALUES (mins, mins || ' min', ord, mins = 1, TRUE)
|
|
ON CONFLICT (interval_minutes) DO NOTHING;
|
|
END LOOP;
|
|
END IF;
|
|
|
|
IF EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_name = 'candle_predict_candles' AND column_name = 'interval_minutes'
|
|
) = FALSE THEN
|
|
ALTER TABLE candle_predict_candles ADD COLUMN interval_minutes INTEGER NOT NULL DEFAULT 1;
|
|
END IF;
|
|
|
|
IF EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_name = 'candle_predict_bets' AND column_name = 'interval_minutes'
|
|
) = FALSE THEN
|
|
ALTER TABLE candle_predict_bets ADD COLUMN interval_minutes INTEGER NOT NULL DEFAULT 1;
|
|
END IF;
|
|
|
|
IF EXISTS (
|
|
SELECT 1 FROM information_schema.table_constraints
|
|
WHERE table_name = 'candle_predict_rounds' AND constraint_name = 'candle_predict_rounds_candle_open_ms_key'
|
|
) THEN
|
|
ALTER TABLE candle_predict_rounds DROP CONSTRAINT candle_predict_rounds_candle_open_ms_key;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_indexes WHERE indexname = 'uq_candle_rounds_open_interval'
|
|
) THEN
|
|
CREATE UNIQUE INDEX uq_candle_rounds_open_interval ON candle_predict_rounds(candle_open_ms, interval_minutes);
|
|
END IF;
|
|
|
|
IF EXISTS (
|
|
SELECT 1 FROM information_schema.table_constraints
|
|
WHERE table_name = 'candle_predict_candles' AND constraint_name = 'candle_predict_candles_candle_open_ms_key'
|
|
) THEN
|
|
ALTER TABLE candle_predict_candles DROP CONSTRAINT candle_predict_candles_candle_open_ms_key;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_indexes WHERE indexname = 'uq_candle_candles_open_interval'
|
|
) THEN
|
|
CREATE UNIQUE INDEX uq_candle_candles_open_interval ON candle_predict_candles(candle_open_ms, interval_minutes);
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_candle_rounds_interval ON candle_predict_rounds(interval_minutes);
|
|
CREATE INDEX IF NOT EXISTS idx_candle_candles_interval ON candle_predict_candles(interval_minutes);
|
|
CREATE INDEX IF NOT EXISTS idx_candle_bets_interval ON candle_predict_bets(interval_minutes);
|
|
|
|
CREATE TABLE IF NOT EXISTS candle_predict_auto_settings (
|
|
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
|
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
|
direction VARCHAR(10) CHECK (direction IN ('short', 'long')),
|
|
stake_display NUMERIC(18,6) NOT NULL DEFAULT 1,
|
|
mode VARCHAR(20) NOT NULL DEFAULT 'each_round' CHECK (mode IN ('each_round', 'interval')),
|
|
interval_seconds INTEGER DEFAULT 60,
|
|
period_minutes INTEGER NOT NULL DEFAULT 1,
|
|
last_auto_bet_at TIMESTAMPTZ,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_auto_settings' AND column_name = 'period_minutes'
|
|
) THEN
|
|
ALTER TABLE candle_predict_auto_settings ADD COLUMN period_minutes INTEGER NOT NULL DEFAULT 1;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_auto_settings' AND column_name = 'stake_account_kind'
|
|
) THEN
|
|
ALTER TABLE candle_predict_auto_settings ADD COLUMN stake_account_kind VARCHAR(16) NOT NULL DEFAULT 'main'
|
|
CHECK (stake_account_kind IN ('main', 'bonus'));
|
|
END IF;
|
|
END $$;
|
|
|
|
-- Phase 1 security: user withdrawal controls & surveillance
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'withdrawals_suspended'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN withdrawals_suspended BOOLEAN NOT NULL DEFAULT FALSE;
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'under_surveillance'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN under_surveillance BOOLEAN NOT NULL DEFAULT FALSE;
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'security_suspended_at'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN security_suspended_at TIMESTAMPTZ;
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'security_reason_encrypted'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN security_reason_encrypted TEXT;
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_users_withdrawals_suspended ON users(withdrawals_suspended) WHERE withdrawals_suspended = TRUE;
|
|
CREATE INDEX IF NOT EXISTS idx_users_under_surveillance ON users(under_surveillance) WHERE under_surveillance = TRUE;
|
|
|
|
CREATE TABLE IF NOT EXISTS security_alerts (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
|
severity VARCHAR(20) NOT NULL DEFAULT 'high' CHECK (severity IN ('low', 'medium', 'high', 'critical')),
|
|
alert_type VARCHAR(64) NOT NULL,
|
|
status VARCHAR(32) NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'investigating', 'resolved', 'dismissed')),
|
|
title VARCHAR(255) NOT NULL,
|
|
details_encrypted TEXT,
|
|
metadata JSONB,
|
|
resolved_by UUID REFERENCES users(id),
|
|
resolved_at TIMESTAMPTZ,
|
|
resolution_note_encrypted TEXT,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_security_alerts_status ON security_alerts(status);
|
|
CREATE INDEX IF NOT EXISTS idx_security_alerts_user ON security_alerts(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_security_alerts_created ON security_alerts(created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_security_alerts_type ON security_alerts(alert_type);
|
|
|
|
-- Phase 2 treasury: cold storage (watch-only addresses) and deposit sweeps
|
|
CREATE TABLE IF NOT EXISTS cold_wallets (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
address VARCHAR(255) NOT NULL,
|
|
label VARCHAR(100),
|
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_cold_wallets_type ON cold_wallets(wallet_type_id);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_cold_wallets_active_type ON cold_wallets(wallet_type_id) WHERE is_active = TRUE;
|
|
|
|
CREATE TABLE IF NOT EXISTS deposit_sweeps (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
from_address VARCHAR(255) NOT NULL,
|
|
to_cold_address VARCHAR(255) NOT NULL,
|
|
amount BIGINT NOT NULL,
|
|
blockchain_tx_id VARCHAR(255),
|
|
status VARCHAR(32) NOT NULL DEFAULT 'pending'
|
|
CHECK (status IN ('pending', 'gas_funding', 'broadcasting', 'completed', 'failed', 'skipped')),
|
|
deposit_transaction_id UUID REFERENCES transactions(id),
|
|
error_message_encrypted TEXT,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_deposit_sweeps_deposit_tx ON deposit_sweeps(deposit_transaction_id)
|
|
WHERE deposit_transaction_id IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_deposit_sweeps_status ON deposit_sweeps(status);
|
|
CREATE INDEX IF NOT EXISTS idx_deposit_sweeps_user ON deposit_sweeps(user_id);
|
|
|
|
-- Phase 3: ledger integrity snapshots (detect direct DB balance tampering)
|
|
CREATE TABLE IF NOT EXISTS ledger_integrity_snapshots (
|
|
account_id UUID PRIMARY KEY REFERENCES ledger_accounts(id) ON DELETE CASCADE,
|
|
available_balance BIGINT NOT NULL,
|
|
locked_balance BIGINT NOT NULL,
|
|
entries_sum BIGINT NOT NULL,
|
|
last_entry_at TIMESTAMPTZ,
|
|
snapshot_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
-- Phase 4: in-app admin notifications
|
|
CREATE TABLE IF NOT EXISTS admin_notifications (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
title VARCHAR(255) NOT NULL,
|
|
body_encrypted TEXT,
|
|
severity VARCHAR(20) NOT NULL DEFAULT 'info'
|
|
CHECK (severity IN ('info', 'low', 'medium', 'high', 'critical')),
|
|
alert_id UUID REFERENCES security_alerts(id) ON DELETE SET NULL,
|
|
read_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_admin_notifications_unread ON admin_notifications(created_at DESC)
|
|
WHERE read_at IS NULL;
|
|
|
|
-- Phase 5: approved ledger credits (bonus / admin adjustment)
|
|
CREATE TABLE IF NOT EXISTS ledger_adjustments (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
adjustment_type VARCHAR(32) NOT NULL CHECK (adjustment_type IN ('bonus', 'admin_adjustment')),
|
|
amount BIGINT NOT NULL CHECK (amount > 0),
|
|
reason_encrypted TEXT NOT NULL,
|
|
approved_by UUID NOT NULL REFERENCES users(id),
|
|
transaction_id UUID REFERENCES transactions(id),
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_user ON ledger_adjustments(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_created ON ledger_adjustments(created_at DESC);
|
|
|
|
-- Referral program & bonus accounts
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'referral_code'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN referral_code VARCHAR(32);
|
|
ALTER TABLE users ADD COLUMN referred_by_user_id UUID REFERENCES users(id);
|
|
ALTER TABLE users ADD COLUMN country_of_residence VARCHAR(2);
|
|
ALTER TABLE users ADD COLUMN nationality VARCHAR(2);
|
|
ALTER TABLE users ADD COLUMN first_deposit_at TIMESTAMPTZ;
|
|
ALTER TABLE users ADD COLUMN first_deposit_transaction_id UUID REFERENCES transactions(id);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'ledger_accounts' AND column_name = 'account_kind'
|
|
) THEN
|
|
ALTER TABLE ledger_accounts ADD COLUMN account_kind VARCHAR(16) NOT NULL DEFAULT 'main'
|
|
CHECK (account_kind IN ('main', 'bonus'));
|
|
ALTER TABLE ledger_accounts DROP CONSTRAINT IF EXISTS ledger_accounts_user_id_wallet_type_id_key;
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_accounts_user_wallet_kind
|
|
ON ledger_accounts(user_id, wallet_type_id, account_kind);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_bets' AND column_name = 'stake_account_kind'
|
|
) THEN
|
|
ALTER TABLE candle_predict_bets ADD COLUMN stake_account_kind VARCHAR(16) NOT NULL DEFAULT 'main'
|
|
CHECK (stake_account_kind IN ('main', 'bonus'));
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_referral_code ON users(referral_code) WHERE referral_code IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_users_referred_by ON users(referred_by_user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_users_country ON users(country_of_residence);
|
|
CREATE INDEX IF NOT EXISTS idx_users_nationality ON users(nationality);
|
|
|
|
CREATE TABLE IF NOT EXISTS referral_program_settings (
|
|
id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
default_referrer_user_id UUID REFERENCES users(id),
|
|
bonus_withdrawable BOOLEAN NOT NULL DEFAULT FALSE,
|
|
referrer_must_be_verified BOOLEAN NOT NULL DEFAULT TRUE,
|
|
referrer_must_have_deposited BOOLEAN NOT NULL DEFAULT TRUE,
|
|
min_first_deposit_raw BIGINT NOT NULL DEFAULT 0,
|
|
commission_wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id) DEFAULT 2,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
INSERT INTO referral_program_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
|
|
|
|
CREATE TABLE IF NOT EXISTS referral_levels (
|
|
level_number INTEGER PRIMARY KEY CHECK (level_number >= 1),
|
|
commission_percent NUMERIC(8,4) NOT NULL CHECK (commission_percent >= 0 AND commission_percent <= 100),
|
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
INSERT INTO referral_levels (level_number, commission_percent) VALUES
|
|
(1, 20.0000),
|
|
(2, 10.0000)
|
|
ON CONFLICT (level_number) DO NOTHING;
|
|
|
|
CREATE TABLE IF NOT EXISTS referral_commission_payouts (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
beneficiary_user_id UUID NOT NULL REFERENCES users(id),
|
|
referred_user_id UUID NOT NULL REFERENCES users(id),
|
|
level_number INTEGER NOT NULL,
|
|
first_deposit_transaction_id UUID NOT NULL REFERENCES transactions(id),
|
|
deposit_amount BIGINT NOT NULL,
|
|
commission_percent NUMERIC(8,4) NOT NULL,
|
|
commission_amount BIGINT NOT NULL,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
UNIQUE (beneficiary_user_id, referred_user_id, first_deposit_transaction_id, level_number)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_beneficiary ON referral_commission_payouts(beneficiary_user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_referred ON referral_commission_payouts(referred_user_id);
|
|
|
|
CREATE TABLE IF NOT EXISTS platform_bonus_pools (
|
|
wallet_type_id INTEGER PRIMARY KEY REFERENCES wallet_types(id),
|
|
available_balance BIGINT NOT NULL DEFAULT 0,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
INSERT INTO platform_bonus_pools (wallet_type_id)
|
|
SELECT id FROM wallet_types WHERE code = 'USDT_TRC20'
|
|
ON CONFLICT DO NOTHING;
|
|
|
|
-- Extend exchange_funding for cold ↔ hot treasury moves (manual confirm workflow)
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'exchange_funding' AND column_name = 'from_address'
|
|
) THEN
|
|
ALTER TABLE exchange_funding ADD COLUMN from_address VARCHAR(255);
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'exchange_funding' AND column_name = 'to_address'
|
|
) THEN
|
|
ALTER TABLE exchange_funding ADD COLUMN to_address VARCHAR(255);
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'exchange_funding' AND column_name = 'notes_encrypted'
|
|
) THEN
|
|
ALTER TABLE exchange_funding ADD COLUMN notes_encrypted TEXT;
|
|
END IF;
|
|
END $$;
|
|
|
|
INSERT INTO advertisements (placement, title, subtitle, cta_label, link_url, background_gradient, accent_color, is_active, sort_order)
|
|
SELECT * FROM (VALUES
|
|
('home_hero', 'Welcome bonus', 'Deposit today and get a 100% match up to $50 on your first wallet top-up.', 'Fund wallet', '/wallet', 'linear-gradient(135deg, rgba(214,178,94,0.35) 0%, rgba(124,92,255,0.25) 100%)', '#D6B25E', TRUE, 1),
|
|
('home_hero', 'Daily spin', 'Spin the wheel every 24h for free credits and bonus multipliers.', 'Play now', '/home', 'linear-gradient(135deg, rgba(124,92,255,0.35) 0%, rgba(41,182,246,0.2) 100%)', '#7C5CFF', TRUE, 2),
|
|
('home_hero', 'Weekend tournament', 'Compete on the Candle Predict leaderboard. Top players share the prize pool.', 'Join tournament', '/games/candle-predict', 'linear-gradient(135deg, rgba(76,175,80,0.3) 0%, rgba(214,178,94,0.2) 100%)', '#4CAF50', TRUE, 3),
|
|
('home_strip', 'Secure wallet', 'USDT (TRC20) deposits with real-time balance tracking.', 'Open wallet', '/wallet', NULL, '#D6B25E', TRUE, 1),
|
|
('home_strip', 'Verify your email', 'Unlock full platform features and faster withdrawals.', 'Verify now', '/profile', NULL, '#7C5CFF', TRUE, 2)
|
|
) 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);
|
|
|
|
-- Dev cleanup: remove legacy TRX / USDC wallet types (platform is USDT-only)
|
|
DO $$
|
|
DECLARE
|
|
legacy_ids INTEGER[];
|
|
usdt_id INTEGER;
|
|
BEGIN
|
|
SELECT ARRAY_AGG(id) INTO legacy_ids FROM wallet_types WHERE code IN ('TRX', 'USDC_POLYGON');
|
|
SELECT id INTO usdt_id FROM wallet_types WHERE code = 'USDT_TRC20' LIMIT 1;
|
|
|
|
IF legacy_ids IS NOT NULL AND array_length(legacy_ids, 1) > 0 THEN
|
|
DELETE FROM referral_commission_payouts WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM candle_predict_bets WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM withdrawal_locks WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM deposit_sweeps WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM exchange_funding WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM deposit_scanner_state WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM ledger_entries
|
|
WHERE account_id IN (SELECT id FROM ledger_accounts WHERE wallet_type_id = ANY(legacy_ids));
|
|
DELETE FROM ledger_accounts WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM transactions WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM user_wallets WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM hot_wallets WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM cold_wallets WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM platform_bonus_pools WHERE wallet_type_id = ANY(legacy_ids);
|
|
DELETE FROM wallet_types WHERE id = ANY(legacy_ids);
|
|
END IF;
|
|
|
|
IF usdt_id IS NOT NULL THEN
|
|
UPDATE referral_program_settings SET commission_wallet_type_id = usdt_id WHERE id = 1;
|
|
INSERT INTO platform_bonus_pools (wallet_type_id) VALUES (usdt_id) ON CONFLICT DO NOTHING;
|
|
END IF;
|
|
END $$;
|
|
|
|
UPDATE advertisements
|
|
SET subtitle = 'USDT (TRC20) deposits with real-time balance tracking.'
|
|
WHERE placement = 'home_strip' AND title = 'Secure wallet';
|
|
|
|
-- Denormalized admin list stats (refreshed incrementally + batch backfill)
|
|
CREATE TABLE IF NOT EXISTS user_admin_stats (
|
|
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
|
main_balance_raw BIGINT NOT NULL DEFAULT 0,
|
|
bonus_balance_raw BIGINT NOT NULL DEFAULT 0,
|
|
total_bonus_received_raw BIGINT NOT NULL DEFAULT 0,
|
|
prediction_count INTEGER NOT NULL DEFAULT 0,
|
|
total_stake_raw BIGINT NOT NULL DEFAULT 0,
|
|
total_payout_raw BIGINT NOT NULL DEFAULT 0,
|
|
net_pnl_raw BIGINT NOT NULL DEFAULT 0,
|
|
last_login_at TIMESTAMPTZ,
|
|
last_bet_at TIMESTAMPTZ,
|
|
last_activity_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_user_admin_stats_main_balance ON user_admin_stats(main_balance_raw);
|
|
CREATE INDEX IF NOT EXISTS idx_user_admin_stats_net_pnl ON user_admin_stats(net_pnl_raw);
|
|
CREATE INDEX IF NOT EXISTS idx_user_admin_stats_prediction_count ON user_admin_stats(prediction_count);
|
|
CREATE INDEX IF NOT EXISTS idx_user_admin_stats_bonus_received ON user_admin_stats(total_bonus_received_raw);
|
|
CREATE INDEX IF NOT EXISTS idx_user_admin_stats_last_activity ON user_admin_stats(last_activity_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_user_admin_stats_last_login ON user_admin_stats(last_login_at DESC NULLS LAST);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_users_created_at ON users(created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_audit_logs_user_action_created
|
|
ON audit_logs(user_id, action, created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_user_type
|
|
ON ledger_adjustments(user_id, adjustment_type);
|
|
|
|
-- Persistent admin user export jobs (single-instance worker + local files)
|
|
CREATE TABLE IF NOT EXISTS admin_export_jobs (
|
|
id UUID PRIMARY KEY,
|
|
requested_by UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
status VARCHAR(16) NOT NULL DEFAULT 'queued'
|
|
CHECK (status IN ('queued', 'running', 'completed', 'failed')),
|
|
progress INTEGER NOT NULL DEFAULT 0,
|
|
row_count INTEGER NOT NULL DEFAULT 0,
|
|
total_estimate INTEGER,
|
|
error TEXT,
|
|
file_name VARCHAR(255),
|
|
file_path TEXT,
|
|
request_payload JSONB NOT NULL,
|
|
format VARCHAR(8) NOT NULL DEFAULT 'xlsx' CHECK (format IN ('xlsx', 'csv', 'pdf')),
|
|
max_rows INTEGER NOT NULL,
|
|
columns JSONB NOT NULL,
|
|
job_kind VARCHAR(16) NOT NULL DEFAULT 'users' CHECK (job_kind IN ('users', 'reports')),
|
|
report_key VARCHAR(64),
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
started_at TIMESTAMPTZ,
|
|
completed_at TIMESTAMPTZ,
|
|
locked_at TIMESTAMPTZ,
|
|
locked_by VARCHAR(128)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_admin_export_jobs_status_created
|
|
ON admin_export_jobs(status, created_at ASC);
|
|
CREATE INDEX IF NOT EXISTS idx_admin_export_jobs_requested_by
|
|
ON admin_export_jobs(requested_by, created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_admin_export_jobs_expires
|
|
ON admin_export_jobs(expires_at);
|
|
|
|
-- Per-user bet aggregates by game (extend with UNION ALL when new games are added)
|
|
CREATE OR REPLACE VIEW user_game_bet_stats AS
|
|
SELECT
|
|
user_id,
|
|
'candle-predict'::varchar AS game_key,
|
|
COUNT(*)::int AS bet_count,
|
|
COALESCE(SUM(stake_raw), 0)::bigint AS total_stake_raw,
|
|
COALESCE(SUM(payout_raw), 0)::bigint AS total_payout_raw,
|
|
MAX(created_at) AS last_bet_at
|
|
FROM candle_predict_bets
|
|
GROUP BY user_id;
|
|
|
|
-- Test wallet: play-money account kind + admin configuration
|
|
CREATE TABLE IF NOT EXISTS test_wallet_settings (
|
|
id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
credit_amount_raw BIGINT NOT NULL DEFAULT 1000000000,
|
|
max_requests_per_user INTEGER NOT NULL DEFAULT 5 CHECK (max_requests_per_user >= 0),
|
|
cooldown_hours INTEGER NOT NULL DEFAULT 24 CHECK (cooldown_hours >= 0),
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
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;
|
|
|
|
CREATE TABLE IF NOT EXISTS test_wallet_credits (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
|
amount_raw BIGINT NOT NULL CHECK (amount_raw > 0),
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_test_wallet_credits_user ON test_wallet_credits(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_test_wallet_credits_created ON test_wallet_credits(created_at DESC);
|
|
|
|
DO $$
|
|
DECLARE
|
|
r RECORD;
|
|
BEGIN
|
|
FOR r IN
|
|
SELECT conname
|
|
FROM pg_constraint
|
|
WHERE conrelid = 'ledger_accounts'::regclass
|
|
AND contype = 'c'
|
|
AND pg_get_constraintdef(oid) LIKE '%account_kind%'
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE ledger_accounts DROP CONSTRAINT %I', r.conname);
|
|
END LOOP;
|
|
ALTER TABLE ledger_accounts ADD CONSTRAINT ledger_accounts_account_kind_check
|
|
CHECK (account_kind IN ('main', 'bonus', 'test'));
|
|
|
|
FOR r IN
|
|
SELECT conname
|
|
FROM pg_constraint
|
|
WHERE conrelid = 'candle_predict_bets'::regclass
|
|
AND contype = 'c'
|
|
AND pg_get_constraintdef(oid) LIKE '%stake_account_kind%'
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE candle_predict_bets DROP CONSTRAINT %I', r.conname);
|
|
END LOOP;
|
|
ALTER TABLE candle_predict_bets ADD CONSTRAINT candle_predict_bets_stake_account_kind_check
|
|
CHECK (stake_account_kind IN ('main', 'bonus', 'test'));
|
|
|
|
FOR r IN
|
|
SELECT conname
|
|
FROM pg_constraint
|
|
WHERE conrelid = 'candle_predict_auto_settings'::regclass
|
|
AND contype = 'c'
|
|
AND pg_get_constraintdef(oid) LIKE '%stake_account_kind%'
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE candle_predict_auto_settings DROP CONSTRAINT %I', r.conname);
|
|
END LOOP;
|
|
ALTER TABLE candle_predict_auto_settings ADD CONSTRAINT candle_predict_auto_settings_stake_account_kind_check
|
|
CHECK (stake_account_kind IN ('main', 'bonus', 'test'));
|
|
END $$;
|
|
|
|
-- Repair test wallet ledger entries created before reference_id was linked
|
|
UPDATE ledger_entries le
|
|
SET reference_id = twc.id
|
|
FROM ledger_accounts la
|
|
JOIN test_wallet_credits twc
|
|
ON twc.user_id = la.user_id AND twc.wallet_type_id = la.wallet_type_id
|
|
WHERE le.account_id = la.id
|
|
AND le.type = 'test_credit'
|
|
AND le.reference_type = 'test_wallet_credit'
|
|
AND le.reference_id IS NULL
|
|
AND twc.amount_raw = le.amount
|
|
AND ABS(EXTRACT(EPOCH FROM (twc.created_at - le.created_at))) < 30;
|
|
|
|
-- Pool neutrality: min gap (close pools) and max imbalance (one-sided pools)
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'tie_tolerance_max_percent'
|
|
) THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_max_percent NUMERIC(5,2) NOT NULL DEFAULT 95.00;
|
|
ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_min_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
ALTER TABLE candle_predict_config ADD COLUMN tie_tolerance_max_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_intervals' AND column_name = 'tie_tolerance_max_percent'
|
|
) THEN
|
|
ALTER TABLE candle_predict_intervals ADD COLUMN tie_tolerance_max_percent NUMERIC(5,2);
|
|
ALTER TABLE candle_predict_intervals ADD COLUMN tie_tolerance_min_enabled BOOLEAN;
|
|
ALTER TABLE candle_predict_intervals ADD COLUMN tie_tolerance_max_enabled BOOLEAN;
|
|
END IF;
|
|
END $$;
|
|
|
|
-- User gender (male, female, other)
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'gender'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN gender VARCHAR(10) CHECK (gender IN ('male', 'female', 'other'));
|
|
END IF;
|
|
END $$;
|
|
|
|
-- Migration: extend admin_export_jobs for async report exports (existing DBs)
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'admin_export_jobs' AND column_name = 'job_kind'
|
|
) THEN
|
|
ALTER TABLE admin_export_jobs ADD COLUMN job_kind VARCHAR(16) NOT NULL DEFAULT 'users';
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'admin_export_jobs' AND column_name = 'report_key'
|
|
) THEN
|
|
ALTER TABLE admin_export_jobs ADD COLUMN report_key VARCHAR(64);
|
|
END IF;
|
|
END $$;
|
|
|
|
ALTER TABLE admin_export_jobs DROP CONSTRAINT IF EXISTS admin_export_jobs_format_check;
|
|
ALTER TABLE admin_export_jobs ADD CONSTRAINT admin_export_jobs_format_check
|
|
CHECK (format IN ('xlsx', 'csv', 'pdf'));
|
|
|
|
ALTER TABLE admin_export_jobs DROP CONSTRAINT IF EXISTS admin_export_jobs_job_kind_check;
|
|
ALTER TABLE admin_export_jobs ADD CONSTRAINT admin_export_jobs_job_kind_check
|
|
CHECK (job_kind IN ('users', 'reports'));
|
|
|
|
-- Scalability: indexes for high-volume report/analytics queries
|
|
CREATE INDEX IF NOT EXISTS idx_transactions_type_status_created
|
|
ON transactions(type, status, created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_created_at
|
|
ON candle_predict_bets(created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_user_created
|
|
ON candle_predict_bets(user_id, created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_ledger_adjustments_created_at
|
|
ON ledger_adjustments(created_at DESC);
|
|
|
|
-- Daily rollups for dashboard acceleration (refreshed by background job)
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_transactions AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
type,
|
|
status,
|
|
COUNT(*)::bigint AS tx_count,
|
|
COALESCE(SUM(amount), 0)::bigint AS amount_raw,
|
|
COALESCE(MAX(amount), 0)::bigint AS max_amount_raw
|
|
FROM transactions
|
|
GROUP BY 1, 2, 3;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_transactions_pk
|
|
ON analytics_daily_transactions(day, type, status);
|
|
|
|
-- Rebuild bets MV when chart dimensions (direction, interval) are missing
|
|
DO $$
|
|
BEGIN
|
|
IF EXISTS (
|
|
SELECT 1 FROM pg_matviews
|
|
WHERE schemaname = 'public' AND matviewname = 'analytics_daily_bets'
|
|
) AND NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'analytics_daily_bets' AND column_name = 'direction'
|
|
) THEN
|
|
DROP MATERIALIZED VIEW analytics_daily_bets;
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_bets AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
is_auto,
|
|
stake_account_kind,
|
|
status,
|
|
direction,
|
|
interval_minutes,
|
|
COUNT(*)::bigint AS bet_count,
|
|
COALESCE(SUM(stake_raw), 0)::bigint AS stake_raw,
|
|
COALESCE(SUM(payout_raw), 0)::bigint AS payout_raw
|
|
FROM candle_predict_bets
|
|
GROUP BY 1, 2, 3, 4, 5, 6;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_bets_pk
|
|
ON analytics_daily_bets(day, is_auto, stake_account_kind, status, direction, interval_minutes);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_adjustments AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
adjustment_type,
|
|
COUNT(*)::bigint AS adj_count,
|
|
COALESCE(SUM(amount), 0)::bigint AS amount_raw
|
|
FROM ledger_adjustments
|
|
GROUP BY 1, 2;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_adjustments_pk
|
|
ON analytics_daily_adjustments(day, adjustment_type);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_hourly_bets AS
|
|
SELECT
|
|
date_trunc('hour', created_at AT TIME ZONE 'UTC') AS hour_ts,
|
|
COUNT(*)::bigint AS bet_count
|
|
FROM candle_predict_bets
|
|
GROUP BY 1;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_hourly_bets_pk
|
|
ON analytics_hourly_bets(hour_ts);
|
|
|
|
-- Extend transactions MV with max amount for KPI queries (existing DBs)
|
|
DO $$
|
|
BEGIN
|
|
IF EXISTS (
|
|
SELECT 1 FROM pg_matviews
|
|
WHERE schemaname = 'public' AND matviewname = 'analytics_daily_transactions'
|
|
) AND NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'analytics_daily_transactions' AND column_name = 'max_amount_raw'
|
|
) THEN
|
|
DROP MATERIALIZED VIEW analytics_daily_transactions;
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_transactions AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
type,
|
|
status,
|
|
COUNT(*)::bigint AS tx_count,
|
|
COALESCE(SUM(amount), 0)::bigint AS amount_raw,
|
|
COALESCE(MAX(amount), 0)::bigint AS max_amount_raw
|
|
FROM transactions
|
|
GROUP BY 1, 2, 3;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_transactions_pk
|
|
ON analytics_daily_transactions(day, type, status);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_tx_by_user AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
type,
|
|
status,
|
|
user_id,
|
|
COUNT(*)::bigint AS tx_count,
|
|
COALESCE(SUM(amount), 0)::bigint AS amount_raw
|
|
FROM transactions
|
|
WHERE status = 'completed' AND type IN ('deposit', 'withdrawal')
|
|
GROUP BY 1, 2, 3, 4;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_tx_by_user_pk
|
|
ON analytics_daily_tx_by_user(day, type, status, user_id);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_tx_by_country AS
|
|
SELECT
|
|
date_trunc('day', t.created_at AT TIME ZONE 'UTC')::date AS day,
|
|
COALESCE(u.country_of_residence, 'XX') AS country,
|
|
t.type,
|
|
COUNT(*)::bigint AS tx_count,
|
|
COALESCE(SUM(t.amount), 0)::bigint AS amount_raw
|
|
FROM transactions t
|
|
JOIN users u ON u.id = t.user_id
|
|
WHERE t.status = 'completed' AND t.type IN ('deposit', 'withdrawal')
|
|
GROUP BY 1, 2, 3;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_tx_by_country_pk
|
|
ON analytics_daily_tx_by_country(day, country, type);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_bets_by_user AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
user_id,
|
|
is_auto,
|
|
stake_account_kind,
|
|
COUNT(*)::bigint AS bet_count,
|
|
COALESCE(SUM(stake_raw), 0)::bigint AS stake_raw,
|
|
COALESCE(SUM(payout_raw), 0)::bigint AS payout_raw,
|
|
SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END)::bigint AS won_count,
|
|
SUM(CASE WHEN status IN ('won', 'lost') THEN 1 ELSE 0 END)::bigint AS settled_count
|
|
FROM candle_predict_bets
|
|
GROUP BY 1, 2, 3, 4;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_bets_by_user_pk
|
|
ON analytics_daily_bets_by_user(day, user_id, is_auto, stake_account_kind);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_adjustments_by_user AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
adjustment_type,
|
|
user_id,
|
|
COUNT(*)::bigint AS adj_count,
|
|
COALESCE(SUM(amount), 0)::bigint AS amount_raw
|
|
FROM ledger_adjustments
|
|
GROUP BY 1, 2, 3;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_adjustments_by_user_pk
|
|
ON analytics_daily_adjustments_by_user(day, adjustment_type, user_id);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_referrals_by_user AS
|
|
SELECT
|
|
date_trunc('day', created_at AT TIME ZONE 'UTC')::date AS day,
|
|
beneficiary_user_id AS user_id,
|
|
COUNT(*)::bigint AS payout_count,
|
|
COALESCE(SUM(commission_amount), 0)::bigint AS amount_raw
|
|
FROM referral_commission_payouts
|
|
GROUP BY 1, 2;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_referrals_by_user_pk
|
|
ON analytics_daily_referrals_by_user(day, user_id);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_country_user_logins AS
|
|
SELECT
|
|
date_trunc('day', al.created_at AT TIME ZONE 'UTC')::date AS day,
|
|
COALESCE(u.country_of_residence, 'XX') AS country,
|
|
al.user_id
|
|
FROM audit_logs al
|
|
JOIN users u ON u.id = al.user_id
|
|
WHERE al.action = 'login'
|
|
GROUP BY 1, 2, 3;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_country_user_logins_pk
|
|
ON analytics_daily_country_user_logins(day, country, user_id);
|
|
|
|
CREATE MATERIALIZED VIEW IF NOT EXISTS analytics_daily_active_users AS
|
|
SELECT day, user_id FROM (
|
|
SELECT date_trunc('day', al.created_at AT TIME ZONE 'UTC')::date AS day, al.user_id
|
|
FROM audit_logs al
|
|
WHERE al.action = 'login'
|
|
UNION
|
|
SELECT date_trunc('day', b.created_at AT TIME ZONE 'UTC')::date, b.user_id
|
|
FROM candle_predict_bets b
|
|
) active
|
|
GROUP BY day, user_id;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_active_users_pk
|
|
ON analytics_daily_active_users(day, user_id);
|
|
|
|
-- Modular prediction types & multi-candle prediction
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_config' AND column_name = 'prediction_single_enabled'
|
|
) THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN prediction_single_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
ALTER TABLE candle_predict_config ADD COLUMN prediction_auto_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
ALTER TABLE candle_predict_config ADD COLUMN prediction_multi_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE TABLE IF NOT EXISTS candle_predict_multi_levels (
|
|
level SMALLINT PRIMARY KEY CHECK (level >= 2 AND level <= 20),
|
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
-- Payout multiplier: win payout when the full sequence is correct.
|
|
payout_multiplier NUMERIC(8,3) NOT NULL DEFAULT 1 CHECK (payout_multiplier > 0),
|
|
-- Pool multiplier: stake weight in Long/Short pools at the final candle only.
|
|
pool_multiplier NUMERIC(8,3) NOT NULL DEFAULT 1 CHECK (pool_multiplier > 0),
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
-- Separate pool_multiplier from payout_multiplier (pools vs win payout).
|
|
-- Must run before seed INSERT below (existing DBs lack this column until migrated).
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_config'
|
|
AND column_name = 'pool_multiplier'
|
|
) THEN
|
|
ALTER TABLE candle_predict_config ADD COLUMN pool_multiplier NUMERIC(6,3);
|
|
UPDATE candle_predict_config SET pool_multiplier = payout_multiplier WHERE pool_multiplier IS NULL;
|
|
ALTER TABLE candle_predict_config ALTER COLUMN pool_multiplier SET NOT NULL;
|
|
ALTER TABLE candle_predict_config ALTER COLUMN pool_multiplier SET DEFAULT 1.900;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_intervals'
|
|
AND column_name = 'pool_multiplier'
|
|
) THEN
|
|
ALTER TABLE candle_predict_intervals ADD COLUMN pool_multiplier NUMERIC(6,3);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_multi_levels'
|
|
AND column_name = 'pool_multiplier'
|
|
) THEN
|
|
ALTER TABLE candle_predict_multi_levels ADD COLUMN pool_multiplier NUMERIC(8,3);
|
|
UPDATE candle_predict_multi_levels SET pool_multiplier = payout_multiplier WHERE pool_multiplier IS NULL;
|
|
ALTER TABLE candle_predict_multi_levels ALTER COLUMN pool_multiplier SET NOT NULL;
|
|
ALTER TABLE candle_predict_multi_levels ALTER COLUMN pool_multiplier SET DEFAULT 1;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_constraint WHERE conname = 'candle_predict_multi_levels_pool_multiplier_check'
|
|
) THEN
|
|
ALTER TABLE candle_predict_multi_levels
|
|
ADD CONSTRAINT candle_predict_multi_levels_pool_multiplier_check CHECK (pool_multiplier > 0);
|
|
END IF;
|
|
END IF;
|
|
END $$;
|
|
|
|
INSERT INTO candle_predict_multi_levels (level, enabled, payout_multiplier, pool_multiplier, sort_order) VALUES
|
|
(2, TRUE, 3, 3, 1),
|
|
(3, TRUE, 6, 6, 2),
|
|
(4, TRUE, 10, 10, 3),
|
|
(5, TRUE, 15, 15, 4)
|
|
ON CONFLICT (level) DO NOTHING;
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'candle_predict_bets' AND column_name = 'prediction_mode'
|
|
) THEN
|
|
ALTER TABLE candle_predict_bets ADD COLUMN prediction_mode VARCHAR(24) NOT NULL DEFAULT 'single';
|
|
ALTER TABLE candle_predict_bets ADD COLUMN sequence_directions JSONB;
|
|
ALTER TABLE candle_predict_bets ADD COLUMN multi_level SMALLINT;
|
|
ALTER TABLE candle_predict_bets ADD COLUMN sequence_step SMALLINT NOT NULL DEFAULT 0;
|
|
ALTER TABLE candle_predict_bets ADD COLUMN anchor_candle_open_ms BIGINT;
|
|
END IF;
|
|
END $$;
|
|
|
|
UPDATE candle_predict_bets SET prediction_mode = 'single' WHERE prediction_mode IS NULL OR prediction_mode = '';
|
|
|
|
ALTER TABLE candle_predict_bets DROP CONSTRAINT IF EXISTS candle_predict_bets_round_id_user_id_key;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_candle_bets_single_per_round_user
|
|
ON candle_predict_bets(round_id, user_id)
|
|
WHERE prediction_mode = 'single';
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_candle_bets_one_active_multi_per_user_interval
|
|
ON candle_predict_bets(user_id, interval_minutes)
|
|
WHERE prediction_mode = 'multi_candle' AND status = 'in_progress';
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_candle_bets_multi_validation
|
|
ON candle_predict_bets(anchor_candle_open_ms, interval_minutes, sequence_step)
|
|
WHERE prediction_mode = 'multi_candle' AND status = 'in_progress';
|
|
|
|
DO $$
|
|
DECLARE
|
|
r RECORD;
|
|
BEGIN
|
|
FOR r IN
|
|
SELECT conname
|
|
FROM pg_constraint
|
|
WHERE conrelid = 'candle_predict_bets'::regclass
|
|
AND contype = 'c'
|
|
AND pg_get_constraintdef(oid) LIKE '%status%'
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE candle_predict_bets DROP CONSTRAINT %I', r.conname);
|
|
END LOOP;
|
|
ALTER TABLE candle_predict_bets ADD CONSTRAINT candle_predict_bets_status_check
|
|
CHECK (status IN ('pending', 'in_progress', 'won', 'lost', 'refunded'));
|
|
END $$;
|
|
|
|
-- Referral anti-fraud: deferred commissions and referred-user eligibility
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'referred_must_be_verified'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN referred_must_be_verified BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'commission_hold_days'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN commission_hold_days INTEGER NOT NULL DEFAULT 14
|
|
CHECK (commission_hold_days >= 0);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'min_referred_predictions'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN min_referred_predictions INTEGER NOT NULL DEFAULT 10
|
|
CHECK (min_referred_predictions >= 0);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'commission_max_pending_days'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN commission_max_pending_days INTEGER NOT NULL DEFAULT 90
|
|
CHECK (commission_max_pending_days >= 1);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts'
|
|
AND column_name = 'status'
|
|
) THEN
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'pending';
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN eligible_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN paid_at TIMESTAMPTZ;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN rejection_reason TEXT;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN updated_at TIMESTAMPTZ DEFAULT NOW();
|
|
UPDATE referral_commission_payouts
|
|
SET status = 'paid', paid_at = created_at, eligible_at = created_at, updated_at = created_at;
|
|
END IF;
|
|
END $$;
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_constraint WHERE conname = 'referral_commission_payouts_status_check'
|
|
) THEN
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD CONSTRAINT referral_commission_payouts_status_check
|
|
CHECK (status IN ('pending', 'paid', 'rejected', 'expired'));
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_pending
|
|
ON referral_commission_payouts(eligible_at)
|
|
WHERE status = 'pending';
|
|
|
|
DROP MATERIALIZED VIEW IF EXISTS analytics_daily_referrals_by_user;
|
|
CREATE MATERIALIZED VIEW analytics_daily_referrals_by_user AS
|
|
SELECT
|
|
date_trunc('day', COALESCE(paid_at, created_at) AT TIME ZONE 'UTC')::date AS day,
|
|
beneficiary_user_id AS user_id,
|
|
COUNT(*)::bigint AS payout_count,
|
|
COALESCE(SUM(commission_amount), 0)::bigint AS amount_raw
|
|
FROM referral_commission_payouts
|
|
WHERE status = 'paid'
|
|
GROUP BY 1, 2;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_analytics_daily_referrals_by_user_pk
|
|
ON analytics_daily_referrals_by_user(day, user_id);
|
|
|
|
-- Referral anti-fraud P2: Sybil detection, manual review queue, registration IP
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'registration_ip'
|
|
) THEN
|
|
ALTER TABLE users ADD COLUMN registration_ip VARCHAR(45);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'sybil_detection_enabled'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN sybil_detection_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'sybil_review_threshold'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN sybil_review_threshold INTEGER NOT NULL DEFAULT 3
|
|
CHECK (sybil_review_threshold >= 0);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'sybil_block_threshold'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN sybil_block_threshold INTEGER NOT NULL DEFAULT 5
|
|
CHECK (sybil_block_threshold >= 1);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'max_referrals_per_day'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN max_referrals_per_day INTEGER NOT NULL DEFAULT 10
|
|
CHECK (max_referrals_per_day >= 1);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts'
|
|
AND column_name = 'sybil_score'
|
|
) THEN
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN sybil_score INTEGER NOT NULL DEFAULT 0;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN sybil_signals JSONB NOT NULL DEFAULT '[]'::jsonb;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN reviewed_by UUID REFERENCES users(id);
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN reviewed_at TIMESTAMPTZ;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN review_note TEXT;
|
|
END IF;
|
|
END $$;
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF EXISTS (
|
|
SELECT 1 FROM pg_constraint WHERE conname = 'referral_commission_payouts_status_check'
|
|
) THEN
|
|
ALTER TABLE referral_commission_payouts DROP CONSTRAINT referral_commission_payouts_status_check;
|
|
END IF;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD CONSTRAINT referral_commission_payouts_status_check
|
|
CHECK (status IN ('pending', 'review', 'paid', 'rejected', 'expired'));
|
|
EXCEPTION
|
|
WHEN duplicate_object THEN NULL;
|
|
END $$;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_users_registration_ip ON users(registration_ip) WHERE registration_ip IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_audit_logs_ip ON audit_logs(ip_address) WHERE ip_address IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_review
|
|
ON referral_commission_payouts(created_at DESC)
|
|
WHERE status = 'review';
|
|
|
|
-- Referral anti-fraud P3: monthly caps, clawbacks, fraud audit
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'max_commission_amount_per_referrer_month_raw'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN max_commission_amount_per_referrer_month_raw BIGINT NOT NULL DEFAULT 500000000;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'max_commissions_per_referrer_month'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN max_commissions_per_referrer_month INTEGER NOT NULL DEFAULT 50
|
|
CHECK (max_commissions_per_referrer_month >= 0);
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE TABLE IF NOT EXISTS referral_commission_clawbacks (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
payout_id UUID NOT NULL REFERENCES referral_commission_payouts(id),
|
|
beneficiary_user_id UUID NOT NULL REFERENCES users(id),
|
|
amount BIGINT NOT NULL CHECK (amount > 0),
|
|
reason TEXT NOT NULL,
|
|
clawed_by UUID NOT NULL REFERENCES users(id),
|
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_referral_clawbacks_payout ON referral_commission_clawbacks(payout_id);
|
|
CREATE INDEX IF NOT EXISTS idx_referral_clawbacks_beneficiary ON referral_commission_clawbacks(beneficiary_user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_referral_clawbacks_created ON referral_commission_clawbacks(created_at DESC);
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF EXISTS (
|
|
SELECT 1 FROM pg_constraint WHERE conname = 'referral_commission_payouts_status_check'
|
|
) THEN
|
|
ALTER TABLE referral_commission_payouts DROP CONSTRAINT referral_commission_payouts_status_check;
|
|
END IF;
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD CONSTRAINT referral_commission_payouts_status_check
|
|
CHECK (status IN ('pending', 'review', 'paid', 'rejected', 'expired', 'clawed_back'));
|
|
EXCEPTION
|
|
WHEN duplicate_object THEN NULL;
|
|
END $$;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_beneficiary_month
|
|
ON referral_commission_payouts(beneficiary_user_id, created_at DESC);
|
|
|
|
-- Referral refinements: per-MLM-level monthly caps + Slack toggle
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_levels'
|
|
AND column_name = 'monthly_max_amount_raw'
|
|
) THEN
|
|
ALTER TABLE referral_levels
|
|
ADD COLUMN monthly_max_amount_raw BIGINT NOT NULL DEFAULT 0;
|
|
ALTER TABLE referral_levels
|
|
ADD COLUMN monthly_max_count INTEGER NOT NULL DEFAULT 0
|
|
CHECK (monthly_max_count >= 0);
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'slack_alerts_enabled'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN slack_alerts_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
END IF;
|
|
END $$;
|
|
|
|
-- Dual commission modes (deposit + withdrawal) and payout source tracking
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
|
AND column_name = 'deposit_commissions_enabled'
|
|
) THEN
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN deposit_commissions_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
|
ALTER TABLE referral_program_settings
|
|
ADD COLUMN withdrawal_commissions_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts'
|
|
AND column_name = 'commission_source'
|
|
) THEN
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN commission_source VARCHAR(20) NOT NULL DEFAULT 'deposit'
|
|
CHECK (commission_source IN ('deposit', 'withdrawal'));
|
|
ALTER TABLE referral_commission_payouts
|
|
ADD COLUMN withdrawal_transaction_id UUID REFERENCES transactions(id);
|
|
ALTER TABLE referral_commission_payouts
|
|
ALTER COLUMN first_deposit_transaction_id DROP NOT NULL;
|
|
END IF;
|
|
END $$;
|
|
|
|
DO $$
|
|
DECLARE r record;
|
|
BEGIN
|
|
FOR r IN
|
|
SELECT conname FROM pg_constraint
|
|
WHERE conrelid = 'public.referral_commission_payouts'::regclass AND contype = 'u'
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE referral_commission_payouts DROP CONSTRAINT %I', r.conname);
|
|
END LOOP;
|
|
END $$;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_deposit_unique
|
|
ON referral_commission_payouts (beneficiary_user_id, referred_user_id, first_deposit_transaction_id, level_number)
|
|
WHERE commission_source = 'deposit' AND first_deposit_transaction_id IS NOT NULL;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_withdrawal_unique
|
|
ON referral_commission_payouts (beneficiary_user_id, referred_user_id, withdrawal_transaction_id, level_number)
|
|
WHERE commission_source = 'withdrawal' AND withdrawal_transaction_id IS NOT NULL;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_withdrawal_tx
|
|
ON referral_commission_payouts (withdrawal_transaction_id)
|
|
WHERE withdrawal_transaction_id IS NOT NULL;
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_referral_payouts_referred_source
|
|
ON referral_commission_payouts (referred_user_id, commission_source);
|
|
|
|
-- Integrated support messaging (users, visitors, staff)
|
|
CREATE TABLE IF NOT EXISTS support_conversations (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
|
visitor_token VARCHAR(64),
|
|
subject VARCHAR(255),
|
|
status VARCHAR(20) NOT NULL DEFAULT 'open'
|
|
CHECK (status IN ('open', 'pending', 'resolved', 'closed')),
|
|
assigned_to UUID REFERENCES users(id) ON DELETE SET NULL,
|
|
last_message_at TIMESTAMPTZ,
|
|
last_message_preview VARCHAR(500),
|
|
unread_user INTEGER NOT NULL DEFAULT 0,
|
|
unread_staff INTEGER NOT NULL DEFAULT 0,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
CHECK (user_id IS NOT NULL OR (visitor_token IS NOT NULL AND length(visitor_token) >= 16))
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_support_conv_user ON support_conversations(user_id) WHERE user_id IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_support_conv_visitor ON support_conversations(visitor_token) WHERE visitor_token IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_support_conv_status ON support_conversations(status, last_message_at DESC NULLS LAST);
|
|
CREATE INDEX IF NOT EXISTS idx_support_conv_assigned ON support_conversations(assigned_to) WHERE assigned_to IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_support_conv_last_msg ON support_conversations(last_message_at DESC NULLS LAST);
|
|
|
|
CREATE TABLE IF NOT EXISTS support_messages (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
conversation_id UUID NOT NULL REFERENCES support_conversations(id) ON DELETE CASCADE,
|
|
sender_type VARCHAR(10) NOT NULL CHECK (sender_type IN ('user', 'visitor', 'staff')),
|
|
sender_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
|
body TEXT,
|
|
attachment_url VARCHAR(512),
|
|
attachment_name VARCHAR(255),
|
|
attachment_mime VARCHAR(128),
|
|
read_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
CHECK (body IS NOT NULL OR attachment_url IS NOT 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()
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS faq_entries (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
category_id INTEGER NOT NULL REFERENCES faq_categories(id) ON DELETE RESTRICT,
|
|
question VARCHAR(512) NOT NULL,
|
|
answer_html TEXT NOT NULL,
|
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
view_count INTEGER NOT NULL DEFAULT 0,
|
|
helpful_yes INTEGER NOT NULL DEFAULT 0,
|
|
helpful_no INTEGER NOT NULL DEFAULT 0,
|
|
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
|
updated_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_faq_entries_category ON faq_entries(category_id, sort_order);
|
|
CREATE INDEX IF NOT EXISTS idx_faq_entries_active ON faq_entries(is_active, sort_order);
|
|
CREATE INDEX IF NOT EXISTS idx_faq_entries_popular ON faq_entries(view_count DESC) WHERE is_active = TRUE;
|
|
|
|
CREATE TABLE IF NOT EXISTS faq_helpful_votes (
|
|
faq_id UUID NOT NULL REFERENCES faq_entries(id) ON DELETE CASCADE,
|
|
voter_key VARCHAR(128) NOT NULL,
|
|
helpful BOOLEAN NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
PRIMARY KEY (faq_id, voter_key)
|
|
);
|
|
|
|
INSERT INTO faq_categories (slug, name, sort_order) VALUES
|
|
('account', 'Compte', 1),
|
|
('deposits', 'Dépôts', 2),
|
|
('withdrawals', 'Retraits', 3),
|
|
('predictions', 'Prédictions', 4),
|
|
('referral', 'Parrainage', 5),
|
|
('bonus', 'Bonus', 6),
|
|
('security', 'Sécurité', 7)
|
|
ON CONFLICT (slug) DO NOTHING;
|
|
|
|
-- =============================================================================
|
|
-- Database tamper detection (direct SQL / bypass application)
|
|
-- =============================================================================
|
|
|
|
CREATE TABLE IF NOT EXISTS db_tamper_events (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
table_name VARCHAR(128) NOT NULL,
|
|
operation VARCHAR(16) NOT NULL CHECK (operation IN ('INSERT', 'UPDATE', 'DELETE')),
|
|
row_id TEXT,
|
|
old_data JSONB,
|
|
new_data JSONB,
|
|
changed_columns TEXT[],
|
|
source_hint VARCHAR(64) NOT NULL DEFAULT 'direct_database_access',
|
|
severity VARCHAR(20) NOT NULL DEFAULT 'high'
|
|
CHECK (severity IN ('low', 'medium', 'high', 'critical')),
|
|
processed_at TIMESTAMPTZ,
|
|
security_alert_id UUID REFERENCES security_alerts(id) ON DELETE SET NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_db_tamper_events_unprocessed
|
|
ON db_tamper_events(created_at ASC) WHERE processed_at IS NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_db_tamper_events_table ON db_tamper_events(table_name, created_at DESC);
|
|
|
|
CREATE OR REPLACE FUNCTION fn_redact_tamper_row(tbl TEXT, data JSONB)
|
|
RETURNS JSONB AS $$
|
|
DECLARE
|
|
result JSONB := data;
|
|
BEGIN
|
|
IF result IS NULL THEN
|
|
RETURN NULL;
|
|
END IF;
|
|
IF tbl = 'hot_wallets' AND result ? 'encrypted_private_key' THEN
|
|
result := result - 'encrypted_private_key' || jsonb_build_object('encrypted_private_key', '[REDACTED]');
|
|
END IF;
|
|
IF tbl = 'users' THEN
|
|
IF result ? 'password_hash' THEN
|
|
result := result - 'password_hash' || jsonb_build_object('password_hash', '[REDACTED]');
|
|
END IF;
|
|
IF result ? 'totp_secret_encrypted' THEN
|
|
result := result - 'totp_secret_encrypted' || jsonb_build_object('totp_secret_encrypted', '[REDACTED]');
|
|
END IF;
|
|
IF result ? 'email_encrypted' THEN
|
|
result := result - 'email_encrypted' || jsonb_build_object('email_encrypted', '[REDACTED]');
|
|
END IF;
|
|
IF result ? 'phone_encrypted' THEN
|
|
result := result - 'phone_encrypted' || jsonb_build_object('phone_encrypted', '[REDACTED]');
|
|
END IF;
|
|
END IF;
|
|
RETURN result;
|
|
END;
|
|
$$ LANGUAGE plpgsql IMMUTABLE;
|
|
|
|
CREATE OR REPLACE FUNCTION fn_db_tamper_row_id(tbl TEXT, row_data JSONB)
|
|
RETURNS TEXT AS $$
|
|
BEGIN
|
|
IF row_data IS NULL THEN
|
|
RETURN NULL;
|
|
END IF;
|
|
IF row_data ? 'id' THEN
|
|
RETURN row_data ->> 'id';
|
|
END IF;
|
|
IF tbl = 'system_settings' AND row_data ? 'key' THEN
|
|
RETURN row_data ->> 'key';
|
|
END IF;
|
|
RETURN NULL;
|
|
END;
|
|
$$ LANGUAGE plpgsql IMMUTABLE;
|
|
|
|
CREATE OR REPLACE FUNCTION fn_db_tamper_changed_columns(old_row JSONB, new_row JSONB)
|
|
RETURNS TEXT[] AS $$
|
|
SELECT COALESCE(array_agg(key ORDER BY key), ARRAY[]::TEXT[])
|
|
FROM (
|
|
SELECT key FROM jsonb_each(COALESCE(new_row, '{}'::jsonb))
|
|
UNION
|
|
SELECT key FROM jsonb_each(COALESCE(old_row, '{}'::jsonb))
|
|
) keys(key)
|
|
WHERE COALESCE(new_row -> key, 'null'::jsonb) IS DISTINCT FROM COALESCE(old_row -> key, 'null'::jsonb);
|
|
$$ LANGUAGE sql IMMUTABLE;
|
|
|
|
CREATE OR REPLACE FUNCTION fn_db_tamper_base_severity(tbl TEXT)
|
|
RETURNS VARCHAR(20) AS $$
|
|
BEGIN
|
|
RETURN CASE tbl
|
|
WHEN 'hot_wallets' THEN 'critical'
|
|
WHEN 'cold_wallets' THEN 'critical'
|
|
WHEN 'roles' THEN 'critical'
|
|
WHEN 'ledger_entries' THEN 'critical'
|
|
WHEN 'ledger_accounts' THEN 'critical'
|
|
WHEN 'transactions' THEN 'critical'
|
|
WHEN 'ledger_adjustments' THEN 'high'
|
|
WHEN 'users' THEN 'high'
|
|
WHEN 'candle_predict_config' THEN 'high'
|
|
WHEN 'candle_predict_intervals' THEN 'high'
|
|
WHEN 'candle_predict_multi_levels' THEN 'high'
|
|
WHEN 'candle_predict_bets' THEN 'high'
|
|
WHEN 'candle_predict_rounds' THEN 'high'
|
|
WHEN 'test_wallet_credits' THEN 'high'
|
|
WHEN 'test_wallet_settings' THEN 'high'
|
|
WHEN 'referral_program_settings' THEN 'high'
|
|
WHEN 'platform_bonus_pools' THEN 'high'
|
|
WHEN 'exchange_funding' THEN 'high'
|
|
WHEN 'system_settings' THEN 'medium'
|
|
WHEN 'withdrawal_locks' THEN 'medium'
|
|
WHEN 'deposit_scanner_state' THEN 'medium'
|
|
WHEN 'security_alerts' THEN 'high'
|
|
WHEN 'refresh_tokens' THEN 'medium'
|
|
WHEN 'user_wallets' THEN 'high'
|
|
WHEN 'deposit_sweeps' THEN 'high'
|
|
WHEN 'faq_entries' THEN 'medium'
|
|
WHEN 'faq_categories' THEN 'medium'
|
|
WHEN 'referral_commission_payouts' THEN 'high'
|
|
WHEN 'games' THEN 'medium'
|
|
ELSE 'medium'
|
|
END;
|
|
END;
|
|
$$ LANGUAGE plpgsql IMMUTABLE;
|
|
|
|
CREATE OR REPLACE FUNCTION trg_fn_db_tamper_guard()
|
|
RETURNS TRIGGER AS $$
|
|
DECLARE
|
|
authorized TEXT;
|
|
old_j JSONB;
|
|
new_j JSONB;
|
|
cols TEXT[];
|
|
sev VARCHAR(20);
|
|
row_pk TEXT;
|
|
BEGIN
|
|
-- Application legitimately inserts alerts/notifications; only tampering updates/deletes matter.
|
|
IF TG_TABLE_NAME IN ('security_alerts', 'admin_notifications') AND TG_OP = 'INSERT' THEN
|
|
IF TG_OP = 'DELETE' THEN
|
|
RETURN OLD;
|
|
END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
|
|
authorized := current_setting('app.authorized_change', true);
|
|
IF authorized IN ('1', 'true', 'yes') THEN
|
|
IF TG_OP = 'DELETE' THEN
|
|
RETURN OLD;
|
|
END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
|
|
IF TG_OP = 'INSERT' THEN
|
|
old_j := NULL;
|
|
new_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(NEW));
|
|
cols := fn_db_tamper_changed_columns(NULL, new_j);
|
|
ELSIF TG_OP = 'UPDATE' THEN
|
|
old_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(OLD));
|
|
new_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(NEW));
|
|
cols := fn_db_tamper_changed_columns(old_j, new_j);
|
|
IF cols = ARRAY[]::TEXT[] THEN
|
|
RETURN NEW;
|
|
END IF;
|
|
ELSE
|
|
old_j := fn_redact_tamper_row(TG_TABLE_NAME, to_jsonb(OLD));
|
|
new_j := NULL;
|
|
cols := fn_db_tamper_changed_columns(old_j, NULL);
|
|
END IF;
|
|
|
|
sev := fn_db_tamper_base_severity(TG_TABLE_NAME);
|
|
row_pk := fn_db_tamper_row_id(TG_TABLE_NAME, COALESCE(new_j, old_j));
|
|
|
|
IF TG_TABLE_NAME = 'users' AND TG_OP = 'INSERT' THEN
|
|
sev := 'critical';
|
|
ELSIF TG_TABLE_NAME = 'users' AND TG_OP = 'UPDATE' AND (
|
|
'role_id' = ANY(cols) OR 'password_hash' = ANY(cols) OR 'withdrawals_suspended' = ANY(cols)
|
|
OR 'under_surveillance' = ANY(cols) OR 'is_enabled' = ANY(cols)
|
|
) THEN
|
|
sev := 'critical';
|
|
ELSIF TG_TABLE_NAME = 'transactions' AND TG_OP = 'DELETE' THEN
|
|
sev := 'critical';
|
|
ELSIF TG_TABLE_NAME = 'ledger_accounts' AND (
|
|
'available_balance' = ANY(cols) OR 'locked_balance' = ANY(cols)
|
|
) THEN
|
|
sev := 'critical';
|
|
ELSIF TG_TABLE_NAME = 'user_wallets' AND (
|
|
'address' = ANY(cols) OR 'derivation_index' = ANY(cols)
|
|
) THEN
|
|
sev := 'critical';
|
|
ELSIF TG_TABLE_NAME = 'deposit_sweeps' AND (
|
|
'amount' = ANY(cols) OR 'status' = ANY(cols) OR 'blockchain_tx_id' = ANY(cols)
|
|
) THEN
|
|
sev := 'critical';
|
|
END IF;
|
|
|
|
INSERT INTO db_tamper_events (
|
|
table_name, operation, row_id, old_data, new_data, changed_columns, source_hint, severity
|
|
) VALUES (
|
|
TG_TABLE_NAME, TG_OP, row_pk, old_j, new_j, cols, 'direct_database_access', sev
|
|
);
|
|
|
|
IF TG_OP = 'DELETE' THEN
|
|
RETURN OLD;
|
|
END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$ LANGUAGE plpgsql;
|
|
|
|
DO $$
|
|
DECLARE
|
|
tbl TEXT;
|
|
BEGIN
|
|
FOREACH tbl IN ARRAY ARRAY[
|
|
'users', 'roles', 'ledger_accounts', 'ledger_entries', 'transactions',
|
|
'hot_wallets', 'cold_wallets', 'ledger_adjustments',
|
|
'candle_predict_config', 'candle_predict_intervals', 'candle_predict_multi_levels',
|
|
'candle_predict_bets', 'candle_predict_rounds',
|
|
'test_wallet_credits', 'test_wallet_settings',
|
|
'referral_program_settings', 'platform_bonus_pools', 'exchange_funding',
|
|
'system_settings', 'withdrawal_locks', 'deposit_scanner_state',
|
|
'security_alerts', 'refresh_tokens',
|
|
'user_wallets', 'deposit_sweeps',
|
|
'faq_entries', 'faq_categories',
|
|
'referral_commission_payouts', 'games'
|
|
]
|
|
LOOP
|
|
EXECUTE format('DROP TRIGGER IF EXISTS trg_db_tamper_%I ON %I', tbl, tbl);
|
|
EXECUTE format(
|
|
'CREATE TRIGGER trg_db_tamper_%I
|
|
AFTER INSERT OR UPDATE OR DELETE ON %I
|
|
FOR EACH ROW EXECUTE FUNCTION trg_fn_db_tamper_guard()',
|
|
tbl, tbl
|
|
);
|
|
END LOOP;
|
|
END $$;
|