db: replace the migration history with a baseline of the live schema

The migrations did not describe this database, and could not be made to.

Three findings, in the order they surfaced:

  * 25 functions declared across six migrations — all recorded as applied — did
    not exist. Their tables did. Two were reached by the app, so merchant tier
    upgrades and post-trade reputation updates had been quietly dead. This only
    came to light because a user hit "Could not find the function
    public.upsert_user_profile(...)" while toggling a notification setting.

  * admin_roles has three conflicting definitions across the set and production
    matches none of them. 001 says (id, user_id, role, granted_by, granted_at),
    COMBINED says (user_id, role, created_at), production has
    (id, user_id, role, permissions, created_at, updated_at).

  * Applied to an empty database, five migrations fail. The legacy 0NN filenames
    sort before the 14-digit timestamps they depend on — "013" < "20241117054600"
    — so 013 runs before the migration creating the table it alters. The set
    could never have been replayed from scratch.

So it could not be tested, could not rebuild the database, and did not match what
was running. Widening or patching it would have been dressing up a history that
was already fiction.

The baseline is a pg_dump of the live public schema, which matches production by
construction. Privileges are included deliberately: the REVOKEs on
lock_escrow_internal, release_escrow_internal, refund_escrow_internal and
request_withdraw are the 20260725030000 hardening, and dropping them would hand
fund movement back to anon.

Verified step by step against production before committing:
  - applies to an empty database cleanly, after three real obstacles were fixed
    (extensions live in the `extensions` schema, supabase_admin membership,
    platform-level ALTER DEFAULT PRIVILEGES that cannot apply outside Supabase)
  - produces 83 tables / 39 functions / 222 indexes / 360 policies — identical
    counts to production
  - recorded as applied in supabase_migrations without touching the 37 existing
    rows, then dry-run confirmed "up to date — no pending migrations", so the
    next deploy will not try to replay it over live tables
  - drift check now reports "every declared function is present"; the known-gaps
    list drops from 22 entries to zero

The old files move to migrations/archive/ rather than being deleted — they are
the only record of why parts of this look the way they do. Their README says
plainly not to run them, and why.

CI now applies migrations to an empty Postgres on every PR. That check was
impossible while the old set was the starting point; it is the thing that stops
this class of drift from being discovered by a user again.
This commit is contained in:
Satoshi Qazi Muhammed committed 2026-07-31 18:49:59 -07:00
1 parent b20cfc84ef
commit e18ba679be
43 files changed
+10298 -37

No files matched your search

@@ -0,0 +1,255 @@
-- ========================================
-- PezkuwiChain - Initial Database Schema
-- ========================================
-- Run this in Supabase SQL Editor to set up required tables
-- Dashboard → SQL Editor → New Query → Paste & Run
-- ========================================
-- 1. PROFILES TABLE
-- ========================================
-- Stores user profile information and referral data
CREATE TABLE IF NOT EXISTS public.profiles (
id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
username TEXT UNIQUE NOT NULL,
email TEXT,
full_name TEXT,
avatar_url TEXT,
referred_by TEXT,
referral_code TEXT UNIQUE,
referral_count INTEGER DEFAULT 0,
total_referral_rewards DECIMAL(20, 4) DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL,
PRIMARY KEY (id)
);
-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_profiles_username ON public.profiles(username);
CREATE INDEX IF NOT EXISTS idx_profiles_email ON public.profiles(email);
CREATE INDEX IF NOT EXISTS idx_profiles_referral_code ON public.profiles(referral_code);
CREATE INDEX IF NOT EXISTS idx_profiles_referred_by ON public.profiles(referred_by);
-- Enable Row Level Security
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
-- Drop existing policies if they exist
DROP POLICY IF EXISTS "Users can view their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Users can update their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Public profiles are viewable by everyone" ON public.profiles;
-- Create policies
CREATE POLICY "Users can view their own profile"
ON public.profiles FOR SELECT
USING (auth.uid() = id);
CREATE POLICY "Users can update their own profile"
ON public.profiles FOR UPDATE
USING (auth.uid() = id);
CREATE POLICY "Public profiles are viewable by everyone"
ON public.profiles FOR SELECT
USING (true);
-- ========================================
-- 2. ADMIN ROLES TABLE
-- ========================================
-- Stores admin and moderator role assignments
CREATE TABLE IF NOT EXISTS public.admin_roles (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
role TEXT NOT NULL CHECK (role IN ('admin', 'super_admin', 'moderator')),
granted_by UUID REFERENCES auth.users(id),
granted_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL,
UNIQUE(user_id)
);
-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_admin_roles_user_id ON public.admin_roles(user_id);
-- Enable Row Level Security
ALTER TABLE public.admin_roles ENABLE ROW LEVEL SECURITY;
-- Drop existing policies if they exist
DROP POLICY IF EXISTS "Admins can view admin roles" ON public.admin_roles;
DROP POLICY IF EXISTS "Super admins can manage admin roles" ON public.admin_roles;
-- Create policies
CREATE POLICY "Admins can view admin roles"
ON public.admin_roles FOR SELECT
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('admin', 'super_admin')
)
);
CREATE POLICY "Super admins can manage admin roles"
ON public.admin_roles FOR ALL
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role = 'super_admin'
)
);
-- ========================================
-- 3. WALLETS TABLE
-- ========================================
-- Stores user wallet addresses and metadata
CREATE TABLE IF NOT EXISTS public.wallets (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
address TEXT NOT NULL,
network TEXT NOT NULL DEFAULT 'pezkuwichain',
is_primary BOOLEAN DEFAULT false,
nickname TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL,
last_used_at TIMESTAMP WITH TIME ZONE,
UNIQUE(user_id, address, network)
);
-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_wallets_user_id ON public.wallets(user_id);
CREATE INDEX IF NOT EXISTS idx_wallets_address ON public.wallets(address);
-- Enable Row Level Security
ALTER TABLE public.wallets ENABLE ROW LEVEL SECURITY;
-- Drop existing policies if they exist
DROP POLICY IF EXISTS "Users can view their own wallets" ON public.wallets;
DROP POLICY IF EXISTS "Users can manage their own wallets" ON public.wallets;
-- Create policies
CREATE POLICY "Users can view their own wallets"
ON public.wallets FOR SELECT
USING (auth.uid() = user_id);
CREATE POLICY "Users can manage their own wallets"
ON public.wallets FOR ALL
USING (auth.uid() = user_id);
-- ========================================
-- 4. REFERRAL TRACKING TABLE
-- ========================================
-- Tracks referral rewards and history
CREATE TABLE IF NOT EXISTS public.referral_history (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
referrer_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
referred_user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
referral_code TEXT NOT NULL,
reward_amount DECIMAL(20, 4) DEFAULT 0,
reward_token TEXT DEFAULT 'PEZ',
reward_claimed BOOLEAN DEFAULT false,
claimed_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL,
UNIQUE(referred_user_id)
);
-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_referral_history_referrer ON public.referral_history(referrer_id);
CREATE INDEX IF NOT EXISTS idx_referral_history_referred ON public.referral_history(referred_user_id);
-- Enable Row Level Security
ALTER TABLE public.referral_history ENABLE ROW LEVEL SECURITY;
-- Drop existing policies if they exist
DROP POLICY IF EXISTS "Users can view their referral history" ON public.referral_history;
-- Create policies
CREATE POLICY "Users can view their referral history"
ON public.referral_history FOR SELECT
USING (auth.uid() = referrer_id OR auth.uid() = referred_user_id);
-- ========================================
-- 5. FUNCTIONS
-- ========================================
-- Function to auto-generate referral code on profile creation
CREATE OR REPLACE FUNCTION public.generate_referral_code()
RETURNS TRIGGER AS $$
DECLARE
new_code TEXT;
code_exists BOOLEAN;
BEGIN
-- Generate a random 8-character referral code
LOOP
new_code := UPPER(SUBSTRING(MD5(RANDOM()::TEXT) FROM 1 FOR 8));
-- Check if code already exists
SELECT EXISTS(SELECT 1 FROM public.profiles WHERE referral_code = new_code) INTO code_exists;
-- Exit loop if code is unique
EXIT WHEN NOT code_exists;
END LOOP;
NEW.referral_code := new_code;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Function to update updated_at timestamp
CREATE OR REPLACE FUNCTION public.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- ========================================
-- 6. TRIGGERS
-- ========================================
-- Drop existing triggers if they exist
DROP TRIGGER IF EXISTS trigger_generate_referral_code ON public.profiles;
DROP TRIGGER IF EXISTS trigger_update_profiles_updated_at ON public.profiles;
-- Auto-generate referral code when profile is created
CREATE TRIGGER trigger_generate_referral_code
BEFORE INSERT ON public.profiles
FOR EACH ROW
WHEN (NEW.referral_code IS NULL)
EXECUTE FUNCTION public.generate_referral_code();
-- Auto-update updated_at timestamp
CREATE TRIGGER trigger_update_profiles_updated_at
BEFORE UPDATE ON public.profiles
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();
-- ========================================
-- 7. INITIAL DATA (OPTIONAL)
-- ========================================
-- Add founder as super admin (if exists)
-- Note: Replace 'founder-001' with actual founder user ID after first login
-- This is commented out by default for security
-- INSERT INTO public.admin_roles (user_id, role, granted_by)
-- VALUES ('founder-001', 'super_admin', 'founder-001')
-- ON CONFLICT (user_id) DO NOTHING;
-- ========================================
-- SUCCESS MESSAGE
-- ========================================
DO $$
BEGIN
RAISE NOTICE '========================================';
RAISE NOTICE 'Database schema created successfully!';
RAISE NOTICE '========================================';
RAISE NOTICE 'Tables created:';
RAISE NOTICE ' - profiles';
RAISE NOTICE ' - admin_roles';
RAISE NOTICE ' - wallets';
RAISE NOTICE ' - referral_history';
RAISE NOTICE '';
RAISE NOTICE 'Next steps:';
RAISE NOTICE '1. Test sign up on the web app';
RAISE NOTICE '2. Check if profile is created automatically';
RAISE NOTICE '3. Assign admin role manually if needed';
RAISE NOTICE '========================================';
END $$;
@@ -0,0 +1,79 @@
-- ========================================
-- Add Missing Columns to Profiles Table
-- ========================================
-- Run this in Supabase SQL Editor
-- Dashboard → SQL Editor → New Query → Paste & Run
-- Add bio column
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS bio TEXT;
-- Add phone column
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS phone TEXT;
-- Add language column (default: 'en')
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS language TEXT DEFAULT 'en';
-- Add theme column (default: 'dark')
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS theme TEXT DEFAULT 'dark';
-- Add notification preferences
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS notifications_email BOOLEAN DEFAULT true;
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS notifications_push BOOLEAN DEFAULT false;
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS notifications_sms BOOLEAN DEFAULT false;
-- Add 2FA column
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS two_factor_enabled BOOLEAN DEFAULT false;
-- Add location and website columns (for completeness)
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS location TEXT;
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS website TEXT;
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS phone_number TEXT;
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS recovery_email TEXT;
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS recovery_email_verified BOOLEAN DEFAULT false;
-- Add email_verified (for compatibility, though we prefer user.email_confirmed_at)
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS email_verified BOOLEAN DEFAULT false;
-- Add joined_at column
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS joined_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW());
-- Add role column
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS role TEXT DEFAULT 'Member';
-- Create indexes for frequently queried columns
CREATE INDEX IF NOT EXISTS idx_profiles_phone ON public.profiles(phone);
CREATE INDEX IF NOT EXISTS idx_profiles_language ON public.profiles(language);
CREATE INDEX IF NOT EXISTS idx_profiles_location ON public.profiles(location);
-- Update existing users' joined_at to their created_at if null
UPDATE public.profiles
SET joined_at = created_at
WHERE joined_at IS NULL;
-- Success message
DO $$
BEGIN
RAISE NOTICE 'Profile columns added successfully!';
END $$;
@@ -0,0 +1,48 @@
-- ========================================
-- Fix Profile Creation Issue
-- ========================================
-- Adds INSERT policy and makes username nullable
-- Make username nullable and add default (must be done before policies)
ALTER TABLE public.profiles
ALTER COLUMN username DROP NOT NULL;
ALTER TABLE public.profiles
ALTER COLUMN username SET DEFAULT '';
-- Drop ALL existing policies to start fresh
DROP POLICY IF EXISTS "Users can view their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Users can update their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Public profiles are viewable by everyone" ON public.profiles;
DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles;
-- Recreate policies with proper permissions
-- SELECT: Users can view their own profile
CREATE POLICY "Users can view their own profile"
ON public.profiles FOR SELECT
USING (auth.uid() = id);
-- INSERT: Users can create their own profile only
CREATE POLICY "Users can insert their own profile"
ON public.profiles FOR INSERT
WITH CHECK (auth.uid() = id);
-- UPDATE: Users can update their own profile only
CREATE POLICY "Users can update their own profile"
ON public.profiles FOR UPDATE
USING (auth.uid() = id)
WITH CHECK (auth.uid() = id);
-- PUBLIC SELECT: Allow everyone to view public profile info
CREATE POLICY "Public profiles are viewable by everyone"
ON public.profiles FOR SELECT
USING (true);
-- Success message
DO $$
BEGIN
RAISE NOTICE '========================================';
RAISE NOTICE 'Profile creation fix applied successfully!';
RAISE NOTICE 'Users can now create and update their profiles.';
RAISE NOTICE '========================================';
END $$;
@@ -0,0 +1,97 @@
-- ========================================
-- Create Secure Upsert Function for Profiles
-- ========================================
-- Uses SECURITY DEFINER to bypass RLS for authenticated users
-- First, ensure username is nullable
ALTER TABLE public.profiles
ALTER COLUMN username DROP NOT NULL;
ALTER TABLE public.profiles
ALTER COLUMN username SET DEFAULT '';
-- Create secure upsert function
CREATE OR REPLACE FUNCTION public.upsert_user_profile(
p_username TEXT DEFAULT '',
p_full_name TEXT DEFAULT NULL,
p_bio TEXT DEFAULT NULL,
p_phone_number TEXT DEFAULT NULL,
p_location TEXT DEFAULT NULL,
p_website TEXT DEFAULT NULL,
p_language TEXT DEFAULT 'en',
p_theme TEXT DEFAULT 'dark',
p_notifications_email BOOLEAN DEFAULT true,
p_notifications_push BOOLEAN DEFAULT false,
p_notifications_sms BOOLEAN DEFAULT false
)
RETURNS public.profiles AS $$
DECLARE
result public.profiles;
BEGIN
-- Use auth.uid() to ensure user can only upsert their own profile
INSERT INTO public.profiles (
id,
username,
full_name,
bio,
phone_number,
location,
website,
language,
theme,
notifications_email,
notifications_push,
notifications_sms,
updated_at
)
VALUES (
auth.uid(),
p_username,
p_full_name,
p_bio,
p_phone_number,
p_location,
p_website,
p_language,
p_theme,
p_notifications_email,
p_notifications_push,
p_notifications_sms,
NOW()
)
ON CONFLICT (id)
DO UPDATE SET
username = COALESCE(NULLIF(EXCLUDED.username, ''), profiles.username, ''),
full_name = COALESCE(EXCLUDED.full_name, profiles.full_name),
bio = COALESCE(EXCLUDED.bio, profiles.bio),
phone_number = COALESCE(EXCLUDED.phone_number, profiles.phone_number),
location = COALESCE(EXCLUDED.location, profiles.location),
website = COALESCE(EXCLUDED.website, profiles.website),
language = COALESCE(EXCLUDED.language, profiles.language),
theme = COALESCE(EXCLUDED.theme, profiles.theme),
notifications_email = COALESCE(EXCLUDED.notifications_email, profiles.notifications_email),
notifications_push = COALESCE(EXCLUDED.notifications_push, profiles.notifications_push),
notifications_sms = COALESCE(EXCLUDED.notifications_sms, profiles.notifications_sms),
updated_at = NOW()
RETURNING *
INTO result;
RETURN result;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Grant execute permission to authenticated users only
GRANT EXECUTE ON FUNCTION public.upsert_user_profile TO authenticated;
-- Revoke from public for security
REVOKE EXECUTE ON FUNCTION public.upsert_user_profile FROM PUBLIC;
-- Success message
DO $$
BEGIN
RAISE NOTICE '========================================';
RAISE NOTICE 'Profile upsert function created successfully!';
RAISE NOTICE 'Function: upsert_user_profile()';
RAISE NOTICE 'This bypasses RLS using SECURITY DEFINER';
RAISE NOTICE '========================================';
END $$;
@@ -0,0 +1,216 @@
-- Forum Tables for Pezkuwi Governance
-- Admin Announcements Table
CREATE TABLE IF NOT EXISTS public.admin_announcements (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
content TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'info', -- 'info', 'warning', 'success', 'critical'
is_active BOOLEAN DEFAULT true,
priority INTEGER DEFAULT 0, -- Higher priority shows first
created_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Forum Categories
CREATE TABLE IF NOT EXISTS public.forum_categories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL UNIQUE,
description TEXT,
icon TEXT,
color TEXT,
display_order INTEGER DEFAULT 0,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Forum Discussions
CREATE TABLE IF NOT EXISTS public.forum_discussions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
category_id UUID REFERENCES public.forum_categories(id) ON DELETE SET NULL,
proposal_id TEXT, -- Link to blockchain proposal if applicable
title TEXT NOT NULL,
content TEXT NOT NULL,
author_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
author_name TEXT NOT NULL,
author_address TEXT, -- Blockchain address
is_pinned BOOLEAN DEFAULT false,
is_locked BOOLEAN DEFAULT false,
views_count INTEGER DEFAULT 0,
replies_count INTEGER DEFAULT 0,
tags TEXT[],
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
last_activity_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Forum Replies
CREATE TABLE IF NOT EXISTS public.forum_replies (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
discussion_id UUID REFERENCES public.forum_discussions(id) ON DELETE CASCADE,
parent_reply_id UUID REFERENCES public.forum_replies(id) ON DELETE CASCADE, -- For nested replies
content TEXT NOT NULL,
author_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
author_name TEXT NOT NULL,
author_address TEXT,
is_edited BOOLEAN DEFAULT false,
edited_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Discussion Reactions (upvotes/downvotes)
CREATE TABLE IF NOT EXISTS public.forum_reactions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
discussion_id UUID REFERENCES public.forum_discussions(id) ON DELETE CASCADE,
reply_id UUID REFERENCES public.forum_replies(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
reaction_type TEXT NOT NULL, -- 'upvote', 'downvote', 'helpful', etc.
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(discussion_id, user_id, reaction_type),
UNIQUE(reply_id, user_id, reaction_type)
);
-- Create Indexes
CREATE INDEX IF NOT EXISTS idx_announcements_active ON public.admin_announcements(is_active, priority DESC, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_discussions_category ON public.forum_discussions(category_id);
CREATE INDEX IF NOT EXISTS idx_discussions_proposal ON public.forum_discussions(proposal_id);
CREATE INDEX IF NOT EXISTS idx_discussions_pinned ON public.forum_discussions(is_pinned DESC, last_activity_at DESC);
CREATE INDEX IF NOT EXISTS idx_replies_discussion ON public.forum_replies(discussion_id, created_at);
CREATE INDEX IF NOT EXISTS idx_reactions_discussion ON public.forum_reactions(discussion_id);
CREATE INDEX IF NOT EXISTS idx_reactions_reply ON public.forum_reactions(reply_id);
-- RLS Policies
-- Admin Announcements
ALTER TABLE public.admin_announcements ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view active announcements"
ON public.admin_announcements FOR SELECT
USING (is_active = true AND (expires_at IS NULL OR expires_at > NOW()));
CREATE POLICY "Admins can manage announcements"
ON public.admin_announcements FOR ALL
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
-- Forum Categories
ALTER TABLE public.forum_categories ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view active categories"
ON public.forum_categories FOR SELECT
USING (is_active = true);
CREATE POLICY "Admins can manage categories"
ON public.forum_categories FOR ALL
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
-- Forum Discussions
ALTER TABLE public.forum_discussions ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view discussions"
ON public.forum_discussions FOR SELECT
USING (true);
CREATE POLICY "Authenticated users can create discussions"
ON public.forum_discussions FOR INSERT
WITH CHECK (auth.uid() IS NOT NULL);
CREATE POLICY "Authors and admins can update discussions"
ON public.forum_discussions FOR UPDATE
USING (
author_id = auth.uid() OR
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
CREATE POLICY "Authors and admins can delete discussions"
ON public.forum_discussions FOR DELETE
USING (
author_id = auth.uid() OR
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
-- Forum Replies
ALTER TABLE public.forum_replies ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view replies"
ON public.forum_replies FOR SELECT
USING (true);
CREATE POLICY "Authenticated users can create replies"
ON public.forum_replies FOR INSERT
WITH CHECK (auth.uid() IS NOT NULL);
CREATE POLICY "Authors and admins can update replies"
ON public.forum_replies FOR UPDATE
USING (
author_id = auth.uid() OR
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
CREATE POLICY "Authors and admins can delete replies"
ON public.forum_replies FOR DELETE
USING (
author_id = auth.uid() OR
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
-- Forum Reactions
ALTER TABLE public.forum_reactions ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view reactions"
ON public.forum_reactions FOR SELECT
USING (true);
CREATE POLICY "Authenticated users can manage own reactions"
ON public.forum_reactions FOR ALL
USING (user_id = auth.uid());
-- Insert Default Categories
INSERT INTO public.forum_categories (name, description, icon, color, display_order) VALUES
('Treasury', 'Discussions about treasury proposals and funding', '💰', '#10B981', 1),
('Technical', 'Technical discussions and protocol upgrades', '⚙️', '#3B82F6', 2),
('Governance', 'Governance proposals and voting discussions', '🗳️', '#8B5CF6', 3),
('Community', 'Community initiatives and general discussions', '👥', '#F59E0B', 4),
('Support', 'Help and support for using Pezkuwi', '❓', '#6B7280', 5)
ON CONFLICT (name) DO NOTHING;
-- Function to update last_activity
CREATE OR REPLACE FUNCTION update_discussion_activity()
RETURNS TRIGGER AS $$
BEGIN
UPDATE public.forum_discussions
SET
last_activity_at = NOW(),
replies_count = replies_count + 1
WHERE id = NEW.discussion_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER on_reply_created
AFTER INSERT ON public.forum_replies
FOR EACH ROW
EXECUTE FUNCTION update_discussion_activity();
@@ -0,0 +1,85 @@
-- Perwerde (Education) Tables
-- Courses Table (ID comes from blockchain)
CREATE TABLE IF NOT EXISTS public.courses (
id BIGINT PRIMARY KEY, -- Blockchain course_id
owner TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
content_link TEXT, -- IPFS hash
status TEXT NOT NULL DEFAULT 'Active',
created_at TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Enrollments Table
CREATE TABLE IF NOT EXISTS public.enrollments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
student_address TEXT NOT NULL,
course_id BIGINT REFERENCES public.courses(id) ON DELETE CASCADE,
enrolled_at TIMESTAMP WITH TIME ZONE NOT NULL,
completed_at TIMESTAMP WITH TIME ZONE,
points_earned INTEGER DEFAULT 0,
is_completed BOOLEAN DEFAULT false,
UNIQUE(student_address, course_id)
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_courses_status ON public.courses(status);
CREATE INDEX IF NOT EXISTS idx_enrollments_student ON public.enrollments(student_address);
CREATE INDEX IF NOT EXISTS idx_enrollments_course ON public.enrollments(course_id);
-- RLS Policies
-- Courses
ALTER TABLE public.courses ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Anyone can view courses" ON public.courses;
CREATE POLICY "Anyone can view courses"
ON public.courses FOR SELECT
USING (true);
DROP POLICY IF EXISTS "Admins can manage courses" ON public.courses;
CREATE POLICY "Admins can manage courses"
ON public.courses FOR ALL
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
-- Enrollments
ALTER TABLE public.enrollments ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Users can view their own enrollments" ON public.enrollments;
CREATE POLICY "Users can view their own enrollments"
ON public.enrollments FOR SELECT
USING (
EXISTS (
SELECT 1 FROM public.wallets
WHERE user_id = auth.uid() AND address = student_address
)
);
DROP POLICY IF EXISTS "Users can create their own enrollments" ON public.enrollments;
CREATE POLICY "Users can create their own enrollments"
ON public.enrollments FOR INSERT
WITH CHECK (
EXISTS (
SELECT 1 FROM public.wallets
WHERE user_id = auth.uid() AND address = student_address
)
);
DROP POLICY IF EXISTS "Admins or course owners can update enrollments" ON public.enrollments;
CREATE POLICY "Admins or course owners can update enrollments"
ON public.enrollments FOR UPDATE
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
) OR
EXISTS (
SELECT 1 FROM public.courses c
JOIN public.wallets w ON c.owner = w.address
WHERE c.id = course_id AND w.user_id = auth.uid()
)
);
@@ -0,0 +1,276 @@
-- =====================================================
-- P2P ATOMIC ESCROW & PLATFORM WALLET SYSTEM
-- Migration: 013_p2p_atomic_escrow.sql
-- =====================================================
-- 1. Platform escrow wallet tracking table
CREATE TABLE IF NOT EXISTS p2p_platform_escrow (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
offer_id UUID NOT NULL REFERENCES p2p_fiat_offers(id) ON DELETE CASCADE,
seller_id UUID NOT NULL REFERENCES auth.users(id),
seller_wallet TEXT NOT NULL,
token TEXT NOT NULL,
amount DECIMAL(20, 12) NOT NULL,
locked_at TIMESTAMPTZ DEFAULT NOW(),
released_at TIMESTAMPTZ,
released_to TEXT, -- wallet address
release_reason TEXT, -- 'trade_complete', 'trade_cancelled', 'trade_expired', 'refund'
blockchain_tx_lock TEXT, -- tx hash for lock transfer
blockchain_tx_release TEXT, -- tx hash for release transfer
status TEXT NOT NULL DEFAULT 'locked' CHECK (status IN ('locked', 'released', 'pending_release')),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Index for quick lookups
CREATE INDEX IF NOT EXISTS idx_platform_escrow_offer ON p2p_platform_escrow(offer_id);
CREATE INDEX IF NOT EXISTS idx_platform_escrow_seller ON p2p_platform_escrow(seller_id);
CREATE INDEX IF NOT EXISTS idx_platform_escrow_status ON p2p_platform_escrow(status);
-- 2. Atomic function to accept offer (prevents race condition)
CREATE OR REPLACE FUNCTION accept_p2p_offer(
p_offer_id UUID,
p_buyer_id UUID,
p_buyer_wallet TEXT,
p_amount DECIMAL(20, 12)
) RETURNS JSON AS $$
DECLARE
v_offer RECORD;
v_trade_id UUID;
v_payment_deadline TIMESTAMPTZ;
v_fiat_amount DECIMAL(20, 2);
BEGIN
-- Lock the offer row for update (prevents concurrent modifications)
SELECT * INTO v_offer
FROM p2p_fiat_offers
WHERE id = p_offer_id
FOR UPDATE;
-- Validation checks
IF v_offer IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Offer not found');
END IF;
IF v_offer.status != 'open' THEN
RETURN json_build_object('success', false, 'error', 'Offer is not available');
END IF;
IF v_offer.seller_id = p_buyer_id THEN
RETURN json_build_object('success', false, 'error', 'Cannot buy from your own offer');
END IF;
IF p_amount > v_offer.remaining_amount THEN
RETURN json_build_object('success', false, 'error', 'Insufficient remaining amount. Available: ' || v_offer.remaining_amount);
END IF;
IF v_offer.min_order_amount IS NOT NULL AND p_amount < v_offer.min_order_amount THEN
RETURN json_build_object('success', false, 'error', 'Minimum order: ' || v_offer.min_order_amount || ' ' || v_offer.token);
END IF;
IF v_offer.max_order_amount IS NOT NULL AND p_amount > v_offer.max_order_amount THEN
RETURN json_build_object('success', false, 'error', 'Maximum order: ' || v_offer.max_order_amount || ' ' || v_offer.token);
END IF;
-- Calculate fiat amount
v_fiat_amount := (p_amount / v_offer.amount_crypto) * v_offer.fiat_amount;
v_payment_deadline := NOW() + (v_offer.time_limit_minutes || ' minutes')::INTERVAL;
-- Create trade
INSERT INTO p2p_fiat_trades (
offer_id,
seller_id,
buyer_id,
buyer_wallet,
crypto_amount,
fiat_amount,
price_per_unit,
escrow_locked_amount,
escrow_locked_at,
status,
payment_deadline
) VALUES (
p_offer_id,
v_offer.seller_id,
p_buyer_id,
p_buyer_wallet,
p_amount,
v_fiat_amount,
v_offer.price_per_unit,
p_amount,
NOW(),
'pending',
v_payment_deadline
) RETURNING id INTO v_trade_id;
-- Atomically update remaining amount
UPDATE p2p_fiat_offers
SET
remaining_amount = remaining_amount - p_amount,
status = CASE
WHEN remaining_amount - p_amount = 0 THEN 'locked'
ELSE 'open'
END,
updated_at = NOW()
WHERE id = p_offer_id;
RETURN json_build_object(
'success', true,
'trade_id', v_trade_id,
'crypto_amount', p_amount,
'fiat_amount', v_fiat_amount,
'payment_deadline', v_payment_deadline
);
END;
$$ LANGUAGE plpgsql;
-- 3. Function to release escrow on trade completion
CREATE OR REPLACE FUNCTION complete_p2p_trade(
p_trade_id UUID,
p_seller_id UUID
) RETURNS JSON AS $$
DECLARE
v_trade RECORD;
BEGIN
-- Lock trade row
SELECT * INTO v_trade
FROM p2p_fiat_trades
WHERE id = p_trade_id
FOR UPDATE;
IF v_trade IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Trade not found');
END IF;
IF v_trade.seller_id != p_seller_id THEN
RETURN json_build_object('success', false, 'error', 'Only seller can confirm receipt');
END IF;
IF v_trade.status != 'payment_sent' THEN
RETURN json_build_object('success', false, 'error', 'Payment not marked as sent yet');
END IF;
-- Update trade status
UPDATE p2p_fiat_trades
SET
status = 'completed',
completed_at = NOW(),
updated_at = NOW()
WHERE id = p_trade_id;
-- Update escrow status (will be released by backend)
UPDATE p2p_platform_escrow
SET
status = 'pending_release',
released_to = v_trade.buyer_wallet,
release_reason = 'trade_complete',
updated_at = NOW()
WHERE offer_id = v_trade.offer_id
AND status = 'locked';
RETURN json_build_object(
'success', true,
'buyer_wallet', v_trade.buyer_wallet,
'amount', v_trade.crypto_amount,
'token', (SELECT token FROM p2p_fiat_offers WHERE id = v_trade.offer_id)
);
END;
$$ LANGUAGE plpgsql;
-- 4. Function to cancel/expire trade (return to seller)
CREATE OR REPLACE FUNCTION cancel_p2p_trade(
p_trade_id UUID,
p_user_id UUID,
p_reason TEXT DEFAULT 'cancelled'
) RETURNS JSON AS $$
DECLARE
v_trade RECORD;
v_offer RECORD;
BEGIN
-- Lock trade row
SELECT * INTO v_trade
FROM p2p_fiat_trades
WHERE id = p_trade_id
FOR UPDATE;
IF v_trade IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Trade not found');
END IF;
-- Only buyer can cancel before payment, or system for expiry
IF v_trade.status = 'pending' AND v_trade.buyer_id != p_user_id THEN
RETURN json_build_object('success', false, 'error', 'Only buyer can cancel pending trade');
END IF;
IF v_trade.status NOT IN ('pending', 'payment_sent') THEN
RETURN json_build_object('success', false, 'error', 'Trade cannot be cancelled in current status');
END IF;
-- Get offer details
SELECT * INTO v_offer FROM p2p_fiat_offers WHERE id = v_trade.offer_id;
-- Update trade status
UPDATE p2p_fiat_trades
SET
status = 'cancelled',
cancelled_at = NOW(),
cancelled_by = p_user_id,
updated_at = NOW()
WHERE id = p_trade_id;
-- Return amount to offer
UPDATE p2p_fiat_offers
SET
remaining_amount = remaining_amount + v_trade.crypto_amount,
status = 'open',
updated_at = NOW()
WHERE id = v_trade.offer_id;
RETURN json_build_object(
'success', true,
'refunded_amount', v_trade.crypto_amount,
'reason', p_reason
);
END;
$$ LANGUAGE plpgsql;
-- 5. RLS policies for platform escrow
ALTER TABLE p2p_platform_escrow ENABLE ROW LEVEL SECURITY;
-- Sellers can view their own escrow
CREATE POLICY "Sellers can view their escrow"
ON p2p_platform_escrow FOR SELECT
USING (seller_id = auth.uid());
-- Admins can view all escrow
CREATE POLICY "Admins can view all escrow"
ON p2p_platform_escrow FOR SELECT
USING (
EXISTS (
SELECT 1 FROM profiles
WHERE profiles.id = auth.uid()
AND profiles.role IN ('admin', 'super_admin')
)
);
-- Only system can insert/update (via service role)
-- No INSERT/UPDATE policies for regular users
-- 6. Add platform_wallet_address to config
CREATE TABLE IF NOT EXISTS p2p_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
description TEXT,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Insert platform wallet config (will be updated with real address)
INSERT INTO p2p_config (key, value, description)
VALUES (
'platform_escrow_wallet',
'5DFwqK698vL4gXHEcanaewnAqhxJ2rjhAogpSTHw3iwGDwd3',
'Platform wallet address for P2P escrow'
)
ON CONFLICT (key) DO NOTHING;
COMMENT ON TABLE p2p_platform_escrow IS 'Tracks all escrow deposits for P2P trades';
COMMENT ON TABLE p2p_config IS 'P2P system configuration';
@@ -0,0 +1,547 @@
-- =====================================================
-- P2P INTERNAL LEDGER ESCROW SYSTEM (OKX Model)
-- Migration: 014_p2p_internal_ledger_escrow.sql
-- Date: 2025-12-11
-- =====================================================
--
-- This migration implements OKX-style internal ledger escrow where:
-- - Blockchain transactions ONLY occur at deposit/withdraw
-- - P2P trades use internal database balance transfers
-- - No blockchain transactions during actual P2P trading
--
-- =====================================================
-- 1. USER INTERNAL BALANCES TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS user_internal_balances (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
token TEXT NOT NULL CHECK (token IN ('HEZ', 'PEZ')),
available_balance DECIMAL(20, 12) NOT NULL DEFAULT 0 CHECK (available_balance >= 0),
locked_balance DECIMAL(20, 12) NOT NULL DEFAULT 0 CHECK (locked_balance >= 0),
total_deposited DECIMAL(20, 12) NOT NULL DEFAULT 0,
total_withdrawn DECIMAL(20, 12) NOT NULL DEFAULT 0,
last_deposit_at TIMESTAMPTZ,
last_withdraw_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(user_id, token)
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_internal_balances_user ON user_internal_balances(user_id);
CREATE INDEX IF NOT EXISTS idx_internal_balances_token ON user_internal_balances(token);
-- RLS
ALTER TABLE user_internal_balances ENABLE ROW LEVEL SECURITY;
-- Users can view their own balances
CREATE POLICY "Users can view own balances"
ON user_internal_balances FOR SELECT
USING (user_id = auth.uid());
-- Only system can modify balances (via service role)
-- No INSERT/UPDATE/DELETE policies for regular users
-- Admins can view all balances
CREATE POLICY "Admins can view all balances"
ON user_internal_balances FOR SELECT
USING (
EXISTS (
SELECT 1 FROM profiles
WHERE profiles.id = auth.uid()
AND profiles.role IN ('admin', 'super_admin')
)
);
-- =====================================================
-- 2. DEPOSIT/WITHDRAW REQUESTS TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS p2p_deposit_withdraw_requests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
request_type TEXT NOT NULL CHECK (request_type IN ('deposit', 'withdraw')),
token TEXT NOT NULL CHECK (token IN ('HEZ', 'PEZ')),
amount DECIMAL(20, 12) NOT NULL CHECK (amount > 0),
wallet_address TEXT NOT NULL,
blockchain_tx_hash TEXT,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled')),
processed_at TIMESTAMPTZ,
processed_by UUID REFERENCES auth.users(id),
error_message TEXT,
notes TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_deposit_withdraw_status ON p2p_deposit_withdraw_requests(status);
CREATE INDEX IF NOT EXISTS idx_deposit_withdraw_user ON p2p_deposit_withdraw_requests(user_id);
CREATE INDEX IF NOT EXISTS idx_deposit_withdraw_type ON p2p_deposit_withdraw_requests(request_type);
-- RLS
ALTER TABLE p2p_deposit_withdraw_requests ENABLE ROW LEVEL SECURITY;
-- Users can view their own requests
CREATE POLICY "Users can view own requests"
ON p2p_deposit_withdraw_requests FOR SELECT
USING (user_id = auth.uid());
-- Users can create their own requests
CREATE POLICY "Users can create own requests"
ON p2p_deposit_withdraw_requests FOR INSERT
WITH CHECK (user_id = auth.uid());
-- Admins can view and manage all requests
CREATE POLICY "Admins can manage all requests"
ON p2p_deposit_withdraw_requests FOR ALL
USING (
EXISTS (
SELECT 1 FROM profiles
WHERE profiles.id = auth.uid()
AND profiles.role IN ('admin', 'super_admin')
)
);
-- =====================================================
-- 3. BALANCE TRANSACTION LOG (Audit Trail)
-- =====================================================
CREATE TABLE IF NOT EXISTS p2p_balance_transactions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
token TEXT NOT NULL,
transaction_type TEXT NOT NULL CHECK (transaction_type IN (
'deposit', 'withdraw', 'escrow_lock', 'escrow_release',
'escrow_refund', 'trade_receive', 'admin_adjustment'
)),
amount DECIMAL(20, 12) NOT NULL,
balance_before DECIMAL(20, 12) NOT NULL,
balance_after DECIMAL(20, 12) NOT NULL,
reference_type TEXT, -- 'offer', 'trade', 'deposit_request', 'withdraw_request'
reference_id UUID,
description TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_balance_tx_user ON p2p_balance_transactions(user_id);
CREATE INDEX IF NOT EXISTS idx_balance_tx_type ON p2p_balance_transactions(transaction_type);
CREATE INDEX IF NOT EXISTS idx_balance_tx_created ON p2p_balance_transactions(created_at DESC);
-- RLS
ALTER TABLE p2p_balance_transactions ENABLE ROW LEVEL SECURITY;
-- Users can view their own transaction history
CREATE POLICY "Users can view own transactions"
ON p2p_balance_transactions FOR SELECT
USING (user_id = auth.uid());
-- =====================================================
-- 4. LOCK ESCROW FUNCTION (Internal Balance)
-- =====================================================
CREATE OR REPLACE FUNCTION lock_escrow_internal(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_reference_type TEXT DEFAULT NULL,
p_reference_id UUID DEFAULT NULL
) RETURNS JSON AS $$
DECLARE
v_balance RECORD;
v_balance_before DECIMAL(20, 12);
BEGIN
-- Lock user's balance row for update
SELECT * INTO v_balance
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token
FOR UPDATE;
-- Check if balance exists
IF v_balance IS NULL THEN
RETURN json_build_object(
'success', false,
'error', 'No balance found for token ' || p_token || '. Please deposit first.'
);
END IF;
v_balance_before := v_balance.available_balance;
-- Check sufficient balance
IF v_balance.available_balance < p_amount THEN
RETURN json_build_object(
'success', false,
'error', 'Insufficient balance. Available: ' || v_balance.available_balance || ' ' || p_token
);
END IF;
-- Move from available to locked
UPDATE user_internal_balances
SET
available_balance = available_balance - p_amount,
locked_balance = locked_balance + p_amount,
updated_at = NOW()
WHERE user_id = p_user_id AND token = p_token;
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'escrow_lock', p_amount,
v_balance_before, v_balance_before - p_amount, p_reference_type, p_reference_id,
'Escrow locked for P2P offer'
);
RETURN json_build_object(
'success', true,
'locked_amount', p_amount,
'available_balance', v_balance_before - p_amount,
'locked_balance', v_balance.locked_balance + p_amount
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 5. RELEASE ESCROW FUNCTION (Trade Completion)
-- =====================================================
CREATE OR REPLACE FUNCTION release_escrow_internal(
p_from_user_id UUID,
p_to_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_reference_type TEXT DEFAULT 'trade',
p_reference_id UUID DEFAULT NULL
) RETURNS JSON AS $$
DECLARE
v_from_balance RECORD;
v_to_balance RECORD;
v_from_balance_before DECIMAL(20, 12);
v_to_balance_before DECIMAL(20, 12);
BEGIN
-- Lock seller's balance row
SELECT * INTO v_from_balance
FROM user_internal_balances
WHERE user_id = p_from_user_id AND token = p_token
FOR UPDATE;
-- Check seller has sufficient locked balance
IF v_from_balance IS NULL OR v_from_balance.locked_balance < p_amount THEN
RETURN json_build_object(
'success', false,
'error', 'Insufficient locked balance for release'
);
END IF;
v_from_balance_before := v_from_balance.locked_balance;
-- Reduce seller's locked balance
UPDATE user_internal_balances
SET
locked_balance = locked_balance - p_amount,
updated_at = NOW()
WHERE user_id = p_from_user_id AND token = p_token;
-- Log seller's transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_from_user_id, p_token, 'escrow_release', -p_amount,
v_from_balance_before, v_from_balance_before - p_amount, p_reference_type, p_reference_id,
'Escrow released to buyer'
);
-- Get or initialize buyer's balance
SELECT available_balance INTO v_to_balance_before
FROM user_internal_balances
WHERE user_id = p_to_user_id AND token = p_token;
IF v_to_balance_before IS NULL THEN
v_to_balance_before := 0;
END IF;
-- Increase buyer's available balance (upsert)
INSERT INTO user_internal_balances (user_id, token, available_balance)
VALUES (p_to_user_id, p_token, p_amount)
ON CONFLICT (user_id, token)
DO UPDATE SET
available_balance = user_internal_balances.available_balance + p_amount,
updated_at = NOW();
-- Log buyer's transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_to_user_id, p_token, 'trade_receive', p_amount,
v_to_balance_before, v_to_balance_before + p_amount, p_reference_type, p_reference_id,
'Received from P2P trade'
);
RETURN json_build_object(
'success', true,
'transferred_amount', p_amount,
'from_user_id', p_from_user_id,
'to_user_id', p_to_user_id
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 6. REFUND ESCROW FUNCTION (Trade Cancellation)
-- =====================================================
CREATE OR REPLACE FUNCTION refund_escrow_internal(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_reference_type TEXT DEFAULT 'trade',
p_reference_id UUID DEFAULT NULL
) RETURNS JSON AS $$
DECLARE
v_balance RECORD;
v_locked_before DECIMAL(20, 12);
BEGIN
-- Lock user's balance row
SELECT * INTO v_balance
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token
FOR UPDATE;
-- Check sufficient locked balance
IF v_balance IS NULL OR v_balance.locked_balance < p_amount THEN
RETURN json_build_object(
'success', false,
'error', 'Insufficient locked balance for refund'
);
END IF;
v_locked_before := v_balance.locked_balance;
-- Move from locked back to available
UPDATE user_internal_balances
SET
locked_balance = locked_balance - p_amount,
available_balance = available_balance + p_amount,
updated_at = NOW()
WHERE user_id = p_user_id AND token = p_token;
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'escrow_refund', p_amount,
v_locked_before, v_locked_before - p_amount, p_reference_type, p_reference_id,
'Escrow refunded (trade cancelled)'
);
RETURN json_build_object(
'success', true,
'refunded_amount', p_amount,
'available_balance', v_balance.available_balance + p_amount,
'locked_balance', v_locked_before - p_amount
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 7. PROCESS DEPOSIT FUNCTION
-- =====================================================
CREATE OR REPLACE FUNCTION process_deposit(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_tx_hash TEXT,
p_request_id UUID DEFAULT NULL
) RETURNS JSON AS $$
DECLARE
v_balance_before DECIMAL(20, 12) := 0;
BEGIN
-- Get current balance
SELECT available_balance INTO v_balance_before
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token;
IF v_balance_before IS NULL THEN
v_balance_before := 0;
END IF;
-- Upsert balance
INSERT INTO user_internal_balances (
user_id, token, available_balance, total_deposited, last_deposit_at
) VALUES (
p_user_id, p_token, p_amount, p_amount, NOW()
)
ON CONFLICT (user_id, token)
DO UPDATE SET
available_balance = user_internal_balances.available_balance + p_amount,
total_deposited = user_internal_balances.total_deposited + p_amount,
last_deposit_at = NOW(),
updated_at = NOW();
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'deposit', p_amount,
v_balance_before, v_balance_before + p_amount, 'deposit_request', p_request_id,
'Deposit from blockchain TX: ' || p_tx_hash
);
-- Update request status if provided
IF p_request_id IS NOT NULL THEN
UPDATE p2p_deposit_withdraw_requests
SET
status = 'completed',
blockchain_tx_hash = p_tx_hash,
processed_at = NOW(),
updated_at = NOW()
WHERE id = p_request_id;
END IF;
RETURN json_build_object(
'success', true,
'deposited_amount', p_amount,
'new_balance', v_balance_before + p_amount
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 8. REQUEST WITHDRAW FUNCTION
-- =====================================================
CREATE OR REPLACE FUNCTION request_withdraw(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_wallet_address TEXT
) RETURNS JSON AS $$
DECLARE
v_balance RECORD;
v_request_id UUID;
BEGIN
-- Lock user's balance
SELECT * INTO v_balance
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token
FOR UPDATE;
-- Check sufficient available balance
IF v_balance IS NULL OR v_balance.available_balance < p_amount THEN
RETURN json_build_object(
'success', false,
'error', 'Insufficient available balance. Available: ' || COALESCE(v_balance.available_balance, 0)
);
END IF;
-- Lock the amount (move to locked_balance)
UPDATE user_internal_balances
SET
available_balance = available_balance - p_amount,
locked_balance = locked_balance + p_amount,
updated_at = NOW()
WHERE user_id = p_user_id AND token = p_token;
-- Create withdrawal request
INSERT INTO p2p_deposit_withdraw_requests (
user_id, request_type, token, amount, wallet_address, status
) VALUES (
p_user_id, 'withdraw', p_token, p_amount, p_wallet_address, 'pending'
) RETURNING id INTO v_request_id;
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'withdraw', -p_amount,
v_balance.available_balance, v_balance.available_balance - p_amount, 'withdraw_request', v_request_id,
'Withdrawal request to ' || p_wallet_address
);
RETURN json_build_object(
'success', true,
'request_id', v_request_id,
'amount', p_amount,
'wallet_address', p_wallet_address,
'status', 'pending'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 9. GET USER BALANCE FUNCTION
-- =====================================================
CREATE OR REPLACE FUNCTION get_user_internal_balance(p_user_id UUID)
RETURNS JSON AS $$
DECLARE
v_balances JSON;
BEGIN
SELECT json_agg(
json_build_object(
'token', token,
'available_balance', available_balance,
'locked_balance', locked_balance,
'total_balance', available_balance + locked_balance,
'total_deposited', total_deposited,
'total_withdrawn', total_withdrawn
)
) INTO v_balances
FROM user_internal_balances
WHERE user_id = p_user_id;
RETURN COALESCE(v_balances, '[]'::json);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 10. HELPER: UPDATE UPDATED_AT TRIGGER
-- =====================================================
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Apply trigger to tables
DROP TRIGGER IF EXISTS update_user_internal_balances_updated_at ON user_internal_balances;
CREATE TRIGGER update_user_internal_balances_updated_at
BEFORE UPDATE ON user_internal_balances
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
DROP TRIGGER IF EXISTS update_deposit_withdraw_requests_updated_at ON p2p_deposit_withdraw_requests;
CREATE TRIGGER update_deposit_withdraw_requests_updated_at
BEFORE UPDATE ON p2p_deposit_withdraw_requests
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-- =====================================================
-- COMMENTS
-- =====================================================
COMMENT ON TABLE user_internal_balances IS 'User internal balances for P2P trading (OKX-style internal ledger)';
COMMENT ON TABLE p2p_deposit_withdraw_requests IS 'Requests for deposits/withdrawals that require blockchain transactions';
COMMENT ON TABLE p2p_balance_transactions IS 'Audit log of all balance changes';
COMMENT ON FUNCTION lock_escrow_internal IS 'Lock user balance for P2P escrow (internal ledger)';
COMMENT ON FUNCTION release_escrow_internal IS 'Release escrow to buyer on trade completion';
COMMENT ON FUNCTION refund_escrow_internal IS 'Refund escrow to seller on trade cancellation';
COMMENT ON FUNCTION process_deposit IS 'Credit user balance after deposit verification';
COMMENT ON FUNCTION request_withdraw IS 'Create withdrawal request and lock balance';
@@ -0,0 +1,714 @@
-- =====================================================
-- Migration 015: Expanded Payment Methods (50+ methods)
-- OKX-Style: 900+ payment methods equivalent regional coverage
-- =====================================================
-- Ensure payment_methods table exists with all fields
CREATE TABLE IF NOT EXISTS payment_methods (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
currency VARCHAR(10) NOT NULL,
country VARCHAR(100) NOT NULL,
method_name VARCHAR(100) NOT NULL,
method_type VARCHAR(50) NOT NULL CHECK (method_type IN ('bank', 'mobile_payment', 'cash', 'crypto_exchange', 'e_wallet', 'card', 'remittance')),
logo_url TEXT,
fields JSONB DEFAULT '{}',
validation_rules JSONB DEFAULT '{}',
min_trade_amount DECIMAL(18,2) DEFAULT 0,
max_trade_amount DECIMAL(18,2),
processing_time_minutes INT DEFAULT 30,
display_order INT DEFAULT 100,
is_active BOOLEAN DEFAULT TRUE,
requires_verification BOOLEAN DEFAULT FALSE,
notes TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Create index for faster queries
CREATE INDEX IF NOT EXISTS idx_payment_methods_currency ON payment_methods(currency);
CREATE INDEX IF NOT EXISTS idx_payment_methods_active ON payment_methods(is_active);
-- =====================================================
-- TURKEY (TRY) - 15 Payment Methods
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order)
VALUES
-- Major Banks
('TRY', 'Turkey', 'Ziraat Bankası', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 1),
('TRY', 'Turkey', 'İş Bankası', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 2),
('TRY', 'Turkey', 'Garanti BBVA', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 3),
('TRY', 'Turkey', 'Akbank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 4),
('TRY', 'Turkey', 'Yapı Kredi', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 5),
('TRY', 'Turkey', 'Halkbank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 6),
('TRY', 'Turkey', 'Vakıfbank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 7),
('TRY', 'Turkey', 'QNB Finansbank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 8),
('TRY', 'Turkey', 'Denizbank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 9),
('TRY', 'Turkey', 'TEB', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 15, 10),
-- E-Wallets & Mobile
('TRY', 'Turkey', 'Papara', 'e_wallet',
'{"papara_number": "Papara Number", "account_holder": "Account Holder Name"}',
'{"papara_number": {"pattern": "^[0-9]{10}$", "required": true}}',
50, 5, 11),
('TRY', 'Turkey', 'Ininal', 'e_wallet',
'{"ininal_number": "Ininal Card Number"}',
'{"ininal_number": {"required": true}}',
50, 5, 12),
('TRY', 'Turkey', 'ENPARA', 'mobile_payment',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 10, 13),
('TRY', 'Turkey', 'Tosla', 'e_wallet',
'{"tosla_number": "Tosla Number"}',
'{"tosla_number": {"required": true}}',
50, 5, 14),
('TRY', 'Turkey', 'PTT', 'remittance',
'{"account_holder": "Recipient Name", "tc_number": "TC Kimlik No"}',
'{"tc_number": {"pattern": "^[0-9]{11}$", "required": true}}',
100, 30, 15)
ON CONFLICT DO NOTHING;
-- =====================================================
-- IRAQ (IQD) - 10 Payment Methods
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order)
VALUES
('IQD', 'Iraq', 'Rasheed Bank', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number"}',
'{"account_number": {"required": true}}',
100000, 30, 1),
('IQD', 'Iraq', 'Rafidain Bank', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number"}',
'{"account_number": {"required": true}}',
100000, 30, 2),
('IQD', 'Iraq', 'Trade Bank of Iraq', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number"}',
'{"account_number": {"required": true}}',
100000, 30, 3),
('IQD', 'Iraq', 'Kurdistan International Bank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN Number"}',
'{"iban": {"required": true}}',
50000, 20, 4),
('IQD', 'Iraq', 'Cihan Bank', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number"}',
'{"account_number": {"required": true}}',
50000, 20, 5),
('IQD', 'Iraq', 'ZainCash', 'mobile_payment',
'{"phone_number": "ZainCash Phone Number"}',
'{"phone_number": {"pattern": "^\\+964[0-9]{10}$", "required": true}}',
10000, 5, 6),
('IQD', 'Iraq', 'AsiaHawala', 'mobile_payment',
'{"phone_number": "AsiaHawala Phone Number"}',
'{"phone_number": {"pattern": "^\\+964[0-9]{10}$", "required": true}}',
10000, 5, 7),
('IQD', 'Iraq', 'FastPay', 'mobile_payment',
'{"phone_number": "FastPay Phone Number", "fastpay_id": "FastPay ID"}',
'{"fastpay_id": {"required": true}}',
10000, 5, 8),
('IQD', 'Iraq', 'Qi Card', 'e_wallet',
'{"card_number": "Qi Card Number"}',
'{"card_number": {"required": true}}',
25000, 10, 9),
('IQD', 'Iraq', 'Cash in Person', 'cash',
'{"city": "City", "meeting_point": "Meeting Point Details"}',
'{"city": {"required": true}}',
50000, 60, 10)
ON CONFLICT DO NOTHING;
-- =====================================================
-- IRAN (IRR) - 10 Payment Methods
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order)
VALUES
('IRR', 'Iran', 'Bank Melli Iran', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number", "card_number": "Card Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 1),
('IRR', 'Iran', 'Bank Mellat', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number", "card_number": "Card Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 2),
('IRR', 'Iran', 'Bank Saderat', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 3),
('IRR', 'Iran', 'Bank Tejarat', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 4),
('IRR', 'Iran', 'Parsian Bank', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 5),
('IRR', 'Iran', 'Bank Pasargad', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 6),
('IRR', 'Iran', 'Saman Bank', 'bank',
'{"account_holder": "Account Holder Name", "sheba": "Sheba Number"}',
'{"sheba": {"pattern": "^IR[0-9]{24}$", "required": true}}',
5000000, 30, 7),
('IRR', 'Iran', 'Card to Card', 'card',
'{"card_number": "16-digit Card Number", "account_holder": "Card Holder Name"}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 5, 8),
('IRR', 'Iran', 'Shaparak', 'mobile_payment',
'{"card_number": "Card Number", "mobile": "Mobile Number"}',
'{"card_number": {"required": true}}',
1000000, 5, 9),
('IRR', 'Iran', 'Cash in Person', 'cash',
'{"city": "City", "meeting_point": "Meeting Point Details"}',
'{"city": {"required": true}}',
10000000, 60, 10)
ON CONFLICT DO NOTHING;
-- =====================================================
-- EURO (EUR) - 10 Payment Methods
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order)
VALUES
('EUR', 'Europe', 'SEPA Bank Transfer', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN", "bic": "BIC/SWIFT"}',
'{"iban": {"pattern": "^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$", "required": true}}',
10, 60, 1),
('EUR', 'Europe', 'SEPA Instant', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN"}',
'{"iban": {"pattern": "^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$", "required": true}}',
10, 5, 2),
('EUR', 'Europe', 'N26', 'mobile_payment',
'{"account_holder": "Account Holder Name", "iban": "IBAN"}',
'{"iban": {"required": true}}',
10, 5, 3),
('EUR', 'Europe', 'Revolut', 'e_wallet',
'{"revolut_tag": "Revolut Tag (@username)", "phone": "Phone Number"}',
'{"revolut_tag": {"pattern": "^@[a-z0-9]+$", "required": true}}',
5, 5, 4),
('EUR', 'Europe', 'Wise (TransferWise)', 'e_wallet',
'{"email": "Wise Email", "account_holder": "Account Holder Name"}',
'{"email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
5, 10, 5),
('EUR', 'Europe', 'PayPal', 'e_wallet',
'{"paypal_email": "PayPal Email"}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 5, 6),
('EUR', 'Germany', 'Deutsche Bank', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN", "bic": "BIC"}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
10, 30, 7),
('EUR', 'France', 'BNP Paribas', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN", "bic": "BIC"}',
'{"iban": {"pattern": "^FR[0-9]{25}$", "required": true}}',
10, 30, 8),
('EUR', 'Netherlands', 'ING', 'bank',
'{"account_holder": "Account Holder Name", "iban": "IBAN"}',
'{"iban": {"pattern": "^NL[0-9]{2}[A-Z]{4}[0-9]{10}$", "required": true}}',
10, 30, 9),
('EUR', 'Europe', 'Skrill', 'e_wallet',
'{"skrill_email": "Skrill Email"}',
'{"skrill_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 10, 10)
ON CONFLICT DO NOTHING;
-- =====================================================
-- US DOLLAR (USD) - 10 Payment Methods
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order)
VALUES
('USD', 'United States', 'Zelle', 'mobile_payment',
'{"email_or_phone": "Email or Phone linked to Zelle"}',
'{"email_or_phone": {"required": true}}',
10, 5, 1),
('USD', 'United States', 'Venmo', 'mobile_payment',
'{"venmo_username": "Venmo Username (@)"}',
'{"venmo_username": {"pattern": "^@[a-zA-Z0-9_-]+$", "required": true}}',
10, 5, 2),
('USD', 'United States', 'CashApp', 'mobile_payment',
'{"cashtag": "Cash Tag ($)"}',
'{"cashtag": {"pattern": "^\\$[a-zA-Z0-9_]+$", "required": true}}',
10, 5, 3),
('USD', 'United States', 'PayPal', 'e_wallet',
'{"paypal_email": "PayPal Email"}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 5, 4),
('USD', 'United States', 'Wire Transfer', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number", "routing_number": "Routing Number", "bank_name": "Bank Name"}',
'{"routing_number": {"pattern": "^[0-9]{9}$", "required": true}}',
100, 60, 5),
('USD', 'United States', 'ACH Transfer', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number", "routing_number": "Routing Number"}',
'{"routing_number": {"pattern": "^[0-9]{9}$", "required": true}}',
10, 120, 6),
('USD', 'United States', 'Chase Bank', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number"}',
'{"account_number": {"required": true}}',
10, 30, 7),
('USD', 'United States', 'Bank of America', 'bank',
'{"account_holder": "Account Holder Name", "account_number": "Account Number"}',
'{"account_number": {"required": true}}',
10, 30, 8),
('USD', 'International', 'Wise (TransferWise)', 'e_wallet',
'{"email": "Wise Email", "account_holder": "Account Holder Name"}',
'{"email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
5, 10, 9),
('USD', 'International', 'Western Union', 'remittance',
'{"recipient_name": "Recipient Full Name", "country": "Destination Country"}',
'{"recipient_name": {"required": true}}',
50, 60, 10)
ON CONFLICT DO NOTHING;
-- =====================================================
-- Block Trade Requests Table
-- =====================================================
CREATE TABLE IF NOT EXISTS p2p_block_trade_requests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id),
type VARCHAR(10) NOT NULL CHECK (type IN ('buy', 'sell')),
token VARCHAR(10) NOT NULL,
fiat_currency VARCHAR(10) NOT NULL,
amount DECIMAL(20, 8) NOT NULL,
target_price DECIMAL(20, 8),
message TEXT,
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'negotiating', 'approved', 'in_progress', 'completed', 'cancelled')),
admin_notes TEXT,
assigned_to UUID REFERENCES auth.users(id),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- RLS for block trade requests
ALTER TABLE p2p_block_trade_requests ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can view own block trade requests" ON p2p_block_trade_requests
FOR SELECT USING (user_id = auth.uid());
CREATE POLICY "Users can create block trade requests" ON p2p_block_trade_requests
FOR INSERT WITH CHECK (user_id = auth.uid());
CREATE POLICY "Admins can manage block trade requests" ON p2p_block_trade_requests
FOR ALL USING (
EXISTS (
SELECT 1 FROM profiles
WHERE profiles.id = auth.uid()
AND profiles.role IN ('admin', 'super_admin')
)
);
-- Index for block trade requests
CREATE INDEX IF NOT EXISTS idx_block_trade_user ON p2p_block_trade_requests(user_id);
CREATE INDEX IF NOT EXISTS idx_block_trade_status ON p2p_block_trade_requests(status);
-- =====================================================
-- KURDISH DIASPORA - Germany (EUR) - 8 Payment Methods
-- Large Kurdish population: ~1.5 million
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('EUR', 'Germany', 'Sparkasse', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
10, 30, 20, 'Popular among Kurdish diaspora in Germany'),
('EUR', 'Germany', 'Commerzbank', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
10, 30, 21, NULL),
('EUR', 'Germany', 'Postbank', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
10, 30, 22, NULL),
('EUR', 'Germany', 'DKB', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
10, 30, 23, NULL),
('EUR', 'Germany', 'PayPal DE', 'e_wallet',
'{"paypal_email": "PayPal E-Mail"}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
5, 5, 24, NULL),
('EUR', 'Germany', 'Klarna', 'e_wallet',
'{"klarna_email": "Klarna E-Mail", "phone": "Telefonnummer"}',
'{"klarna_email": {"required": true}}',
10, 10, 25, NULL),
('EUR', 'Germany', 'Azimo (to Kurdistan)', 'remittance',
'{"recipient_name": "Empfängername", "recipient_country": "Zielland"}',
'{"recipient_name": {"required": true}}',
20, 60, 26, 'Money transfer to Kurdistan Region'),
('EUR', 'Germany', 'Western Union DE', 'remittance',
'{"recipient_name": "Empfängername", "mtcn": "MTCN (optional)"}',
'{"recipient_name": {"required": true}}',
50, 30, 27, 'Cash pickup in Kurdistan')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Sweden (SEK) - 6 Payment Methods
-- Kurdish population: ~100,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('SEK', 'Sweden', 'Swish', 'mobile_payment',
'{"phone_number": "Mobilnummer (07x)"}',
'{"phone_number": {"pattern": "^07[0-9]{8}$", "required": true}}',
100, 5, 1, 'Most popular in Sweden'),
('SEK', 'Sweden', 'Nordea', 'bank',
'{"account_holder": "Kontoinnehavare", "clearing": "Clearingnummer", "account": "Kontonummer"}',
'{"clearing": {"pattern": "^[0-9]{4}$", "required": true}}',
100, 30, 2, NULL),
('SEK', 'Sweden', 'SEB', 'bank',
'{"account_holder": "Kontoinnehavare", "iban": "IBAN"}',
'{"iban": {"pattern": "^SE[0-9]{22}$", "required": true}}',
100, 30, 3, NULL),
('SEK', 'Sweden', 'Swedbank', 'bank',
'{"account_holder": "Kontoinnehavare", "iban": "IBAN"}',
'{"iban": {"pattern": "^SE[0-9]{22}$", "required": true}}',
100, 30, 4, NULL),
('SEK', 'Sweden', 'Handelsbanken', 'bank',
'{"account_holder": "Kontoinnehavare", "iban": "IBAN"}',
'{"iban": {"pattern": "^SE[0-9]{22}$", "required": true}}',
100, 30, 5, NULL),
('SEK', 'Sweden', 'Ria Money Transfer', 'remittance',
'{"recipient_name": "Mottagarens namn", "recipient_phone": "Mottagarens telefon"}',
'{"recipient_name": {"required": true}}',
200, 60, 6, 'Send to Kurdistan')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - United Kingdom (GBP) - 8 Payment Methods
-- Kurdish population: ~50,000+
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('GBP', 'United Kingdom', 'Faster Payments', 'bank',
'{"account_holder": "Account Name", "sort_code": "Sort Code", "account_number": "Account Number"}',
'{"sort_code": {"pattern": "^[0-9]{6}$", "required": true}, "account_number": {"pattern": "^[0-9]{8}$", "required": true}}',
10, 5, 1, 'Instant UK bank transfer'),
('GBP', 'United Kingdom', 'Barclays', 'bank',
'{"account_holder": "Account Name", "sort_code": "Sort Code", "account_number": "Account Number"}',
'{"sort_code": {"pattern": "^[0-9]{6}$", "required": true}}',
10, 30, 2, NULL),
('GBP', 'United Kingdom', 'HSBC UK', 'bank',
'{"account_holder": "Account Name", "sort_code": "Sort Code", "account_number": "Account Number"}',
'{"sort_code": {"pattern": "^[0-9]{6}$", "required": true}}',
10, 30, 3, NULL),
('GBP', 'United Kingdom', 'Lloyds Bank', 'bank',
'{"account_holder": "Account Name", "sort_code": "Sort Code", "account_number": "Account Number"}',
'{"sort_code": {"pattern": "^[0-9]{6}$", "required": true}}',
10, 30, 4, NULL),
('GBP', 'United Kingdom', 'Monzo', 'mobile_payment',
'{"monzo_tag": "Monzo.me Username", "phone": "Phone Number"}',
'{"monzo_tag": {"required": true}}',
5, 5, 5, 'Popular digital bank'),
('GBP', 'United Kingdom', 'Revolut UK', 'e_wallet',
'{"revolut_tag": "Revolut Tag (@)", "phone": "Phone Number"}',
'{"revolut_tag": {"pattern": "^@[a-z0-9]+$", "required": true}}',
5, 5, 6, NULL),
('GBP', 'United Kingdom', 'PayPal UK', 'e_wallet',
'{"paypal_email": "PayPal Email"}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 5, 7, NULL),
('GBP', 'United Kingdom', 'WorldRemit', 'remittance',
'{"recipient_name": "Recipient Name", "recipient_phone": "Recipient Phone", "destination": "Destination Country"}',
'{"recipient_name": {"required": true}}',
20, 30, 8, 'Send to Iraq/Kurdistan')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - France (EUR) - 6 Payment Methods
-- Kurdish population: ~200,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('EUR', 'France', 'Crédit Agricole', 'bank',
'{"account_holder": "Titulaire du compte", "iban": "IBAN", "bic": "BIC"}',
'{"iban": {"pattern": "^FR[0-9]{25}$", "required": true}}',
10, 30, 30, NULL),
('EUR', 'France', 'Société Générale', 'bank',
'{"account_holder": "Titulaire du compte", "iban": "IBAN"}',
'{"iban": {"pattern": "^FR[0-9]{25}$", "required": true}}',
10, 30, 31, NULL),
('EUR', 'France', 'La Banque Postale', 'bank',
'{"account_holder": "Titulaire du compte", "iban": "IBAN"}',
'{"iban": {"pattern": "^FR[0-9]{25}$", "required": true}}',
10, 30, 32, 'Popular for remittances'),
('EUR', 'France', 'Lydia', 'mobile_payment',
'{"lydia_phone": "Numéro Lydia"}',
'{"lydia_phone": {"pattern": "^\\+33[0-9]{9}$", "required": true}}',
5, 5, 33, 'Popular mobile payment app'),
('EUR', 'France', 'PayPal FR', 'e_wallet',
'{"paypal_email": "Email PayPal"}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 5, 34, NULL),
('EUR', 'France', 'MoneyGram FR', 'remittance',
'{"recipient_name": "Nom du bénéficiaire", "reference_number": "Numéro de référence"}',
'{"recipient_name": {"required": true}}',
30, 30, 35, 'Cash pickup in Kurdistan')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Netherlands (EUR) - 5 Payment Methods
-- Kurdish population: ~80,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('EUR', 'Netherlands', 'iDEAL', 'bank',
'{"bank_name": "Bank", "account_holder": "Rekeninghouder"}',
'{"bank_name": {"required": true}}',
5, 5, 40, 'Most popular Dutch payment'),
('EUR', 'Netherlands', 'ABN AMRO', 'bank',
'{"account_holder": "Rekeninghouder", "iban": "IBAN"}',
'{"iban": {"pattern": "^NL[0-9]{2}[A-Z]{4}[0-9]{10}$", "required": true}}',
10, 30, 41, NULL),
('EUR', 'Netherlands', 'Rabobank', 'bank',
'{"account_holder": "Rekeninghouder", "iban": "IBAN"}',
'{"iban": {"pattern": "^NL[0-9]{2}[A-Z]{4}[0-9]{10}$", "required": true}}',
10, 30, 42, NULL),
('EUR', 'Netherlands', 'Bunq', 'mobile_payment',
'{"bunq_iban": "Bunq IBAN", "account_holder": "Rekeninghouder"}',
'{"bunq_iban": {"required": true}}',
5, 5, 43, 'Digital bank'),
('EUR', 'Netherlands', 'Tikkie', 'mobile_payment',
'{"tikkie_link": "Tikkie Link or Phone"}',
'{"tikkie_link": {"required": true}}',
5, 5, 44, 'Popular P2P payment')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Belgium (EUR) - 4 Payment Methods
-- Kurdish population: ~50,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('EUR', 'Belgium', 'Bancontact', 'card',
'{"card_number": "Card Number"}',
'{"card_number": {"required": true}}',
10, 5, 50, 'Belgian debit card system'),
('EUR', 'Belgium', 'KBC', 'bank',
'{"account_holder": "Rekeninghouder", "iban": "IBAN"}',
'{"iban": {"pattern": "^BE[0-9]{14}$", "required": true}}',
10, 30, 51, NULL),
('EUR', 'Belgium', 'BNP Paribas Fortis', 'bank',
'{"account_holder": "Rekeninghouder", "iban": "IBAN"}',
'{"iban": {"pattern": "^BE[0-9]{14}$", "required": true}}',
10, 30, 52, NULL),
('EUR', 'Belgium', 'Payconiq', 'mobile_payment',
'{"phone_number": "GSM Nummer"}',
'{"phone_number": {"pattern": "^\\+32[0-9]{9}$", "required": true}}',
5, 5, 53, 'Mobile payment app')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Austria (EUR) - 4 Payment Methods
-- Kurdish population: ~50,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('EUR', 'Austria', 'Erste Bank', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^AT[0-9]{18}$", "required": true}}',
10, 30, 60, NULL),
('EUR', 'Austria', 'Raiffeisen Austria', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^AT[0-9]{18}$", "required": true}}',
10, 30, 61, NULL),
('EUR', 'Austria', 'Bank Austria', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^AT[0-9]{18}$", "required": true}}',
10, 30, 62, NULL),
('EUR', 'Austria', 'EPS', 'bank',
'{"bank_name": "Bank", "account_holder": "Kontoinhaber"}',
'{"bank_name": {"required": true}}',
10, 10, 63, 'Austrian online banking')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Switzerland (CHF) - 4 Payment Methods
-- Kurdish population: ~30,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('CHF', 'Switzerland', 'TWINT', 'mobile_payment',
'{"twint_phone": "Mobile Number"}',
'{"twint_phone": {"pattern": "^\\+41[0-9]{9}$", "required": true}}',
10, 5, 1, 'Most popular Swiss mobile payment'),
('CHF', 'Switzerland', 'UBS', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^CH[0-9]{19}$", "required": true}}',
20, 30, 2, NULL),
('CHF', 'Switzerland', 'Credit Suisse', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^CH[0-9]{19}$", "required": true}}',
20, 30, 3, NULL),
('CHF', 'Switzerland', 'PostFinance', 'bank',
'{"account_holder": "Kontoinhaber", "iban": "IBAN"}',
'{"iban": {"pattern": "^CH[0-9]{19}$", "required": true}}',
20, 30, 4, 'Popular for remittances')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Norway (NOK) - 4 Payment Methods
-- Kurdish population: ~30,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('NOK', 'Norway', 'Vipps', 'mobile_payment',
'{"phone_number": "Mobilnummer"}',
'{"phone_number": {"pattern": "^\\+47[0-9]{8}$", "required": true}}',
100, 5, 1, 'Most popular in Norway'),
('NOK', 'Norway', 'DNB', 'bank',
'{"account_holder": "Kontoinnehaver", "account_number": "Kontonummer"}',
'{"account_number": {"pattern": "^[0-9]{11}$", "required": true}}',
100, 30, 2, NULL),
('NOK', 'Norway', 'Nordea NO', 'bank',
'{"account_holder": "Kontoinnehaver", "account_number": "Kontonummer"}',
'{"account_number": {"pattern": "^[0-9]{11}$", "required": true}}',
100, 30, 3, NULL),
('NOK', 'Norway', 'SpareBank 1', 'bank',
'{"account_holder": "Kontoinnehaver", "account_number": "Kontonummer"}',
'{"account_number": {"pattern": "^[0-9]{11}$", "required": true}}',
100, 30, 4, NULL)
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Denmark (DKK) - 4 Payment Methods
-- Kurdish population: ~25,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('DKK', 'Denmark', 'MobilePay', 'mobile_payment',
'{"phone_number": "Mobilnummer"}',
'{"phone_number": {"pattern": "^\\+45[0-9]{8}$", "required": true}}',
50, 5, 1, 'Most popular in Denmark'),
('DKK', 'Denmark', 'Danske Bank', 'bank',
'{"account_holder": "Kontoindehaver", "reg_number": "Reg. Nr.", "account_number": "Kontonummer"}',
'{"reg_number": {"pattern": "^[0-9]{4}$", "required": true}}',
50, 30, 2, NULL),
('DKK', 'Denmark', 'Nordea DK', 'bank',
'{"account_holder": "Kontoindehaver", "reg_number": "Reg. Nr.", "account_number": "Kontonummer"}',
'{"reg_number": {"pattern": "^[0-9]{4}$", "required": true}}',
50, 30, 3, NULL),
('DKK', 'Denmark', 'Jyske Bank', 'bank',
'{"account_holder": "Kontoindehaver", "reg_number": "Reg. Nr.", "account_number": "Kontonummer"}',
'{"reg_number": {"pattern": "^[0-9]{4}$", "required": true}}',
50, 30, 4, NULL)
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Australia (AUD) - 4 Payment Methods
-- Kurdish population: ~20,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('AUD', 'Australia', 'PayID', 'mobile_payment',
'{"payid": "PayID (Email or Phone)", "account_holder": "Account Name"}',
'{"payid": {"required": true}}',
10, 5, 1, 'Instant Australian payments'),
('AUD', 'Australia', 'Commonwealth Bank', 'bank',
'{"account_holder": "Account Name", "bsb": "BSB", "account_number": "Account Number"}',
'{"bsb": {"pattern": "^[0-9]{6}$", "required": true}}',
10, 30, 2, NULL),
('AUD', 'Australia', 'ANZ', 'bank',
'{"account_holder": "Account Name", "bsb": "BSB", "account_number": "Account Number"}',
'{"bsb": {"pattern": "^[0-9]{6}$", "required": true}}',
10, 30, 3, NULL),
('AUD', 'Australia', 'OSKO', 'bank',
'{"payid": "PayID", "account_holder": "Account Name"}',
'{"payid": {"required": true}}',
10, 5, 4, 'Real-time payments')
ON CONFLICT DO NOTHING;
-- =====================================================
-- KURDISH DIASPORA - Canada (CAD) - 4 Payment Methods
-- Kurdish population: ~30,000
-- =====================================================
INSERT INTO payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, processing_time_minutes, display_order, notes)
VALUES
('CAD', 'Canada', 'Interac e-Transfer', 'mobile_payment',
'{"email": "Email Address", "account_holder": "Account Name"}',
'{"email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 5, 1, 'Most popular in Canada'),
('CAD', 'Canada', 'TD Bank', 'bank',
'{"account_holder": "Account Name", "transit": "Transit Number", "account_number": "Account Number"}',
'{"transit": {"pattern": "^[0-9]{5}$", "required": true}}',
10, 30, 2, NULL),
('CAD', 'Canada', 'RBC', 'bank',
'{"account_holder": "Account Name", "transit": "Transit Number", "account_number": "Account Number"}',
'{"transit": {"pattern": "^[0-9]{5}$", "required": true}}',
10, 30, 3, NULL),
('CAD', 'Canada', 'WISE CAD', 'e_wallet',
'{"email": "Wise Email", "account_holder": "Account Name"}',
'{"email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 15, 4, 'Low-fee international')
ON CONFLICT DO NOTHING;
-- =====================================================
-- Add new currencies to support diaspora
-- =====================================================
-- Note: FiatCurrency type in p2p-fiat.ts needs to be updated to include:
-- SEK (Swedish Krona), GBP (British Pound), CHF (Swiss Franc),
-- NOK (Norwegian Krone), DKK (Danish Krone), AUD (Australian Dollar), CAD (Canadian Dollar)
-- =====================================================
-- Summary: 110+ Payment Methods Total
-- Turkey: 15 (Banks + E-wallets + Mobile)
-- Iraq: 10 (Banks + Mobile + E-wallets + Cash)
-- Iran: 10 (Banks + Card-to-Card + Mobile + Cash)
-- Europe General: 10 (SEPA + Banks + E-wallets)
-- USA: 10 (Mobile + Banks + E-wallets + Remittance)
-- Germany: 8 (Banks + E-wallets + Remittance - Kurdish Diaspora)
-- Sweden: 6 (Banks + Mobile + Remittance - Kurdish Diaspora)
-- UK: 8 (Banks + Mobile + E-wallets + Remittance - Kurdish Diaspora)
-- France: 6 (Banks + Mobile + Remittance - Kurdish Diaspora)
-- Netherlands: 5 (Banks + Mobile - Kurdish Diaspora)
-- Belgium: 4 (Banks + Mobile - Kurdish Diaspora)
-- Austria: 4 (Banks - Kurdish Diaspora)
-- Switzerland: 4 (Banks + Mobile - Kurdish Diaspora)
-- Norway: 4 (Banks + Mobile - Kurdish Diaspora)
-- Denmark: 4 (Banks + Mobile - Kurdish Diaspora)
-- Australia: 4 (Banks + Mobile - Kurdish Diaspora)
-- Canada: 4 (Banks + Mobile - Kurdish Diaspora)
-- =====================================================
@@ -0,0 +1,585 @@
-- =====================================================
-- P2P OKX-LEVEL SECURITY UPGRADE
-- Migration: 016_p2p_okx_security_upgrade.sql
-- Date: 2026-01-29
-- =====================================================
--
-- This migration brings the P2P system to OKX-level security:
-- 1. Deposit verification restricted to service role only
-- 2. TX hash duplicate prevention (UNIQUE constraint)
-- 3. Auto-release removed (disputes instead)
-- 4. Enhanced escrow controls
--
-- =====================================================
-- 1. ADD UNIQUE CONSTRAINT ON TX HASH (Prevent Double-Credit)
-- =====================================================
-- Add unique constraint to prevent same TX being processed twice
DO $$
BEGIN
-- Check if table exists first
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'p2p_deposit_withdraw_requests') THEN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'p2p_deposit_withdraw_requests_tx_hash_unique'
) THEN
ALTER TABLE p2p_deposit_withdraw_requests
ADD CONSTRAINT p2p_deposit_withdraw_requests_tx_hash_unique
UNIQUE (blockchain_tx_hash)
DEFERRABLE INITIALLY DEFERRED;
END IF;
ELSE
RAISE NOTICE 'Table p2p_deposit_withdraw_requests does not exist. Please run migration 014 first.';
END IF;
END $$;
-- Index for faster duplicate checking (only if table exists)
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'p2p_deposit_withdraw_requests') THEN
CREATE INDEX IF NOT EXISTS idx_deposit_withdraw_tx_hash
ON p2p_deposit_withdraw_requests(blockchain_tx_hash)
WHERE blockchain_tx_hash IS NOT NULL;
END IF;
END $$;
-- =====================================================
-- 2. SECURE PROCESS_DEPOSIT FUNCTION (Service Role Only)
-- =====================================================
-- Drop old function and recreate with service role check
DROP FUNCTION IF EXISTS process_deposit(UUID, TEXT, DECIMAL, TEXT, UUID);
CREATE OR REPLACE FUNCTION process_deposit(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_tx_hash TEXT,
p_request_id UUID DEFAULT NULL
) RETURNS JSON AS $$
DECLARE
v_balance_before DECIMAL(20, 12) := 0;
v_existing_tx RECORD;
BEGIN
-- =====================================================
-- SECURITY CHECK: Only service role can call this function
-- This prevents users from crediting their own balance
-- =====================================================
IF current_setting('role', true) != 'service_role' AND
current_setting('request.jwt.claim.role', true) != 'service_role' THEN
RETURN json_build_object(
'success', false,
'error', 'UNAUTHORIZED: Only backend service can process deposits'
);
END IF;
-- =====================================================
-- DUPLICATE CHECK: Prevent same TX hash being processed twice
-- =====================================================
SELECT * INTO v_existing_tx
FROM p2p_deposit_withdraw_requests
WHERE blockchain_tx_hash = p_tx_hash
AND status = 'completed';
IF FOUND THEN
RETURN json_build_object(
'success', false,
'error', 'DUPLICATE: This transaction has already been processed',
'existing_request_id', v_existing_tx.id
);
END IF;
-- =====================================================
-- PROCESS DEPOSIT
-- =====================================================
-- Get current balance
SELECT available_balance INTO v_balance_before
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token;
IF v_balance_before IS NULL THEN
v_balance_before := 0;
END IF;
-- Upsert balance
INSERT INTO user_internal_balances (
user_id, token, available_balance, total_deposited, last_deposit_at
) VALUES (
p_user_id, p_token, p_amount, p_amount, NOW()
)
ON CONFLICT (user_id, token)
DO UPDATE SET
available_balance = user_internal_balances.available_balance + p_amount,
total_deposited = user_internal_balances.total_deposited + p_amount,
last_deposit_at = NOW(),
updated_at = NOW();
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'deposit', p_amount,
v_balance_before, v_balance_before + p_amount, 'deposit_request', p_request_id,
'Verified deposit from blockchain TX: ' || p_tx_hash
);
-- Update request status if provided
IF p_request_id IS NOT NULL THEN
UPDATE p2p_deposit_withdraw_requests
SET
status = 'completed',
blockchain_tx_hash = p_tx_hash,
processed_at = NOW(),
updated_at = NOW()
WHERE id = p_request_id;
END IF;
RETURN json_build_object(
'success', true,
'deposited_amount', p_amount,
'new_balance', v_balance_before + p_amount,
'tx_hash', p_tx_hash
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Revoke execute from authenticated users (only service role)
REVOKE EXECUTE ON FUNCTION process_deposit FROM authenticated;
REVOKE EXECUTE ON FUNCTION process_deposit FROM anon;
-- =====================================================
-- 3. CREATE DEPOSIT REQUEST FUNCTION (User-facing)
-- =====================================================
-- Users submit deposit requests, backend verifies and credits
CREATE OR REPLACE FUNCTION submit_deposit_request(
p_token TEXT,
p_amount DECIMAL(20, 12),
p_tx_hash TEXT,
p_wallet_address TEXT
) RETURNS JSON AS $$
DECLARE
v_user_id UUID;
v_existing_request RECORD;
v_request_id UUID;
BEGIN
-- Get current user
v_user_id := auth.uid();
IF v_user_id IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Not authenticated');
END IF;
-- Validate token
IF p_token NOT IN ('HEZ', 'PEZ') THEN
RETURN json_build_object('success', false, 'error', 'Invalid token');
END IF;
-- Validate amount
IF p_amount <= 0 THEN
RETURN json_build_object('success', false, 'error', 'Amount must be greater than 0');
END IF;
-- Check for existing request with same TX hash
SELECT * INTO v_existing_request
FROM p2p_deposit_withdraw_requests
WHERE blockchain_tx_hash = p_tx_hash;
IF FOUND THEN
RETURN json_build_object(
'success', false,
'error', 'A request with this transaction hash already exists',
'existing_status', v_existing_request.status
);
END IF;
-- Create deposit request (pending verification)
INSERT INTO p2p_deposit_withdraw_requests (
user_id,
request_type,
token,
amount,
wallet_address,
blockchain_tx_hash,
status
) VALUES (
v_user_id,
'deposit',
p_token,
p_amount,
p_wallet_address,
p_tx_hash,
'pending'
) RETURNING id INTO v_request_id;
RETURN json_build_object(
'success', true,
'request_id', v_request_id,
'status', 'pending',
'message', 'Deposit request submitted. Verification typically takes 1-5 minutes.'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Grant execute to authenticated users
GRANT EXECUTE ON FUNCTION submit_deposit_request TO authenticated;
-- =====================================================
-- 4. REMOVE AUTO-RELEASE, ADD DISPUTE TRIGGER
-- =====================================================
-- Replace cancel_expired_trades to NOT auto-release
CREATE OR REPLACE FUNCTION public.cancel_expired_trades()
RETURNS void AS $$
DECLARE
v_trade RECORD;
BEGIN
-- Cancel trades where buyer didn't pay in time
FOR v_trade IN
SELECT * FROM public.p2p_fiat_trades
WHERE status = 'pending'
AND payment_deadline < NOW()
LOOP
-- Update trade status
UPDATE public.p2p_fiat_trades
SET
status = 'cancelled',
cancelled_by = seller_id,
cancellation_reason = 'Payment deadline expired',
updated_at = NOW()
WHERE id = v_trade.id;
-- Refund escrow to seller (internal ledger)
PERFORM refund_escrow_internal(
v_trade.seller_id,
(SELECT token FROM p2p_fiat_offers WHERE id = v_trade.offer_id),
v_trade.crypto_amount,
'trade',
v_trade.id
);
-- Restore offer remaining amount
UPDATE public.p2p_fiat_offers
SET
remaining_amount = remaining_amount + v_trade.crypto_amount,
status = CASE
WHEN status = 'locked' THEN 'open'
ELSE status
END,
updated_at = NOW()
WHERE id = v_trade.offer_id;
-- Update reputation (penalty for buyer)
UPDATE public.p2p_reputation
SET
cancelled_trades = cancelled_trades + 1,
reputation_score = GREATEST(reputation_score - 10, 0),
updated_at = NOW()
WHERE user_id = v_trade.buyer_id;
END LOOP;
-- =====================================================
-- CRITICAL CHANGE: NO AUTO-RELEASE!
-- Instead of auto-releasing, escalate to dispute
-- =====================================================
FOR v_trade IN
SELECT * FROM public.p2p_fiat_trades
WHERE status = 'payment_sent'
AND confirmation_deadline < NOW()
AND status != 'disputed'
LOOP
-- Escalate to dispute instead of auto-releasing
UPDATE public.p2p_fiat_trades
SET
status = 'disputed',
dispute_reason = 'AUTO_ESCALATED: Seller did not confirm payment within time limit',
dispute_opened_at = NOW(),
dispute_opened_by = v_trade.buyer_id,
updated_at = NOW()
WHERE id = v_trade.id;
-- Log suspicious activity
INSERT INTO public.p2p_suspicious_activity (
user_id,
trade_id,
activity_type,
severity,
description,
metadata
) VALUES (
v_trade.seller_id,
v_trade.id,
'other',
'medium',
'Seller did not confirm payment within deadline - auto-escalated to dispute',
jsonb_build_object(
'buyer_id', v_trade.buyer_id,
'crypto_amount', v_trade.crypto_amount,
'payment_sent_at', v_trade.buyer_marked_paid_at,
'confirmation_deadline', v_trade.confirmation_deadline
)
);
-- Notify admins (in production, send push notification/email)
-- For now, just log
END LOOP;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- 5. ADD DISPUTE COLUMNS IF NOT EXISTS
-- =====================================================
DO $$
BEGIN
-- Add dispute columns to trades table
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'p2p_fiat_trades' AND column_name = 'dispute_reason') THEN
ALTER TABLE p2p_fiat_trades ADD COLUMN dispute_reason TEXT;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'p2p_fiat_trades' AND column_name = 'dispute_opened_at') THEN
ALTER TABLE p2p_fiat_trades ADD COLUMN dispute_opened_at TIMESTAMPTZ;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'p2p_fiat_trades' AND column_name = 'dispute_opened_by') THEN
ALTER TABLE p2p_fiat_trades ADD COLUMN dispute_opened_by UUID REFERENCES auth.users(id);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'p2p_fiat_trades' AND column_name = 'dispute_resolved_at') THEN
ALTER TABLE p2p_fiat_trades ADD COLUMN dispute_resolved_at TIMESTAMPTZ;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'p2p_fiat_trades' AND column_name = 'dispute_resolved_by') THEN
ALTER TABLE p2p_fiat_trades ADD COLUMN dispute_resolved_by UUID REFERENCES auth.users(id);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'p2p_fiat_trades' AND column_name = 'dispute_resolution') THEN
ALTER TABLE p2p_fiat_trades ADD COLUMN dispute_resolution TEXT;
END IF;
END $$;
-- =====================================================
-- 6. ADMIN DISPUTE RESOLUTION FUNCTION
-- =====================================================
CREATE OR REPLACE FUNCTION resolve_p2p_dispute(
p_trade_id UUID,
p_resolution TEXT, -- 'release_to_buyer' or 'refund_to_seller'
p_resolution_notes TEXT DEFAULT NULL
) RETURNS JSON AS $$
DECLARE
v_admin_id UUID;
v_trade RECORD;
v_offer RECORD;
BEGIN
-- Get current user (must be admin)
v_admin_id := auth.uid();
-- Check admin role
IF NOT EXISTS (
SELECT 1 FROM profiles
WHERE id = v_admin_id
AND role IN ('admin', 'super_admin', 'moderator')
) THEN
RETURN json_build_object('success', false, 'error', 'Only admins can resolve disputes');
END IF;
-- Get trade
SELECT * INTO v_trade
FROM p2p_fiat_trades
WHERE id = p_trade_id
FOR UPDATE;
IF NOT FOUND THEN
RETURN json_build_object('success', false, 'error', 'Trade not found');
END IF;
IF v_trade.status != 'disputed' THEN
RETURN json_build_object('success', false, 'error', 'Trade is not in disputed status');
END IF;
-- Get offer for token info
SELECT * INTO v_offer
FROM p2p_fiat_offers
WHERE id = v_trade.offer_id;
IF p_resolution = 'release_to_buyer' THEN
-- Release crypto to buyer
PERFORM release_escrow_internal(
v_trade.seller_id,
v_trade.buyer_id,
v_offer.token,
v_trade.crypto_amount,
'dispute_resolution',
p_trade_id
);
-- Update trade status
UPDATE p2p_fiat_trades
SET
status = 'completed',
completed_at = NOW(),
dispute_resolved_at = NOW(),
dispute_resolved_by = v_admin_id,
dispute_resolution = 'Released to buyer: ' || COALESCE(p_resolution_notes, ''),
updated_at = NOW()
WHERE id = p_trade_id;
-- Update reputations (seller gets penalty)
UPDATE p2p_reputation
SET
disputed_trades = disputed_trades + 1,
reputation_score = GREATEST(reputation_score - 20, 0),
updated_at = NOW()
WHERE user_id = v_trade.seller_id;
ELSIF p_resolution = 'refund_to_seller' THEN
-- Refund crypto to seller
PERFORM refund_escrow_internal(
v_trade.seller_id,
v_offer.token,
v_trade.crypto_amount,
'dispute_resolution',
p_trade_id
);
-- Restore offer if needed
UPDATE p2p_fiat_offers
SET
remaining_amount = remaining_amount + v_trade.crypto_amount,
status = CASE WHEN remaining_amount + v_trade.crypto_amount > 0 THEN 'open' ELSE status END,
updated_at = NOW()
WHERE id = v_trade.offer_id;
-- Update trade status
UPDATE p2p_fiat_trades
SET
status = 'refunded',
dispute_resolved_at = NOW(),
dispute_resolved_by = v_admin_id,
dispute_resolution = 'Refunded to seller: ' || COALESCE(p_resolution_notes, ''),
updated_at = NOW()
WHERE id = p_trade_id;
-- Update reputations (buyer gets penalty)
UPDATE p2p_reputation
SET
disputed_trades = disputed_trades + 1,
reputation_score = GREATEST(reputation_score - 20, 0),
updated_at = NOW()
WHERE user_id = v_trade.buyer_id;
ELSE
RETURN json_build_object('success', false, 'error', 'Invalid resolution type');
END IF;
-- Log the resolution
INSERT INTO p2p_audit_log (
user_id,
action,
entity_type,
entity_id,
details
) VALUES (
v_admin_id,
'dispute_resolved',
'trade',
p_trade_id,
jsonb_build_object(
'resolution', p_resolution,
'notes', p_resolution_notes,
'seller_id', v_trade.seller_id,
'buyer_id', v_trade.buyer_id,
'amount', v_trade.crypto_amount
)
);
RETURN json_build_object(
'success', true,
'resolution', p_resolution,
'trade_id', p_trade_id
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Grant to authenticated (function checks admin role internally)
GRANT EXECUTE ON FUNCTION resolve_p2p_dispute TO authenticated;
-- =====================================================
-- 7. ADD 'refunded' TO TRADE STATUS ENUM
-- =====================================================
DO $$
BEGIN
-- Check if constraint exists and update it
ALTER TABLE p2p_fiat_trades
DROP CONSTRAINT IF EXISTS p2p_fiat_trades_status_check;
ALTER TABLE p2p_fiat_trades
ADD CONSTRAINT p2p_fiat_trades_status_check
CHECK (status IN ('pending', 'payment_sent', 'completed', 'cancelled', 'disputed', 'refunded'));
EXCEPTION
WHEN others THEN
-- Constraint might not exist, ignore
NULL;
END $$;
-- =====================================================
-- 8. CREATE P2P_AUDIT_LOG TABLE IF NOT EXISTS
-- =====================================================
CREATE TABLE IF NOT EXISTS p2p_audit_log (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
action TEXT NOT NULL,
entity_type TEXT NOT NULL,
entity_id UUID,
details JSONB DEFAULT '{}',
ip_address INET,
user_agent TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_p2p_audit_log_user ON p2p_audit_log(user_id);
CREATE INDEX IF NOT EXISTS idx_p2p_audit_log_action ON p2p_audit_log(action);
CREATE INDEX IF NOT EXISTS idx_p2p_audit_log_entity ON p2p_audit_log(entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_p2p_audit_log_created ON p2p_audit_log(created_at DESC);
ALTER TABLE p2p_audit_log ENABLE ROW LEVEL SECURITY;
-- Only admins can view audit log
CREATE POLICY "p2p_audit_log_admin_only" ON p2p_audit_log
FOR ALL USING (
EXISTS (
SELECT 1 FROM profiles
WHERE id = auth.uid()
AND role IN ('admin', 'super_admin')
)
);
-- =====================================================
-- COMMENTS
-- =====================================================
COMMENT ON FUNCTION process_deposit IS
'OKX-LEVEL SECURITY: Process deposit - ONLY callable by service role (backend).
Users cannot credit their own balance. Backend must verify TX on-chain first.';
COMMENT ON FUNCTION submit_deposit_request IS
'User-facing function to submit deposit request. Creates pending request that
backend will verify and process using process_deposit().';
COMMENT ON FUNCTION cancel_expired_trades IS
'OKX-LEVEL SECURITY: NO AUTO-RELEASE. Expired confirmation trades are
escalated to dispute for admin review, not auto-released to buyer.';
COMMENT ON FUNCTION resolve_p2p_dispute IS
'Admin function to resolve P2P disputes. Can release to buyer or refund to seller.';
@@ -0,0 +1,211 @@
-- =====================================================
-- Migration 017: Withdraw Completion Function
-- Properly handles successful withdrawal balance updates
-- =====================================================
-- Function to complete a withdrawal (called after blockchain TX success)
CREATE OR REPLACE FUNCTION complete_withdraw(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_tx_hash TEXT,
p_request_id UUID
) RETURNS JSON AS $$
DECLARE
v_balance RECORD;
v_locked_before DECIMAL(20, 12);
BEGIN
-- Get current balance
SELECT * INTO v_balance
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token
FOR UPDATE;
IF v_balance IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Balance record not found');
END IF;
IF v_balance.locked_balance < p_amount THEN
RETURN json_build_object(
'success', false,
'error', 'Insufficient locked balance for withdrawal completion'
);
END IF;
v_locked_before := v_balance.locked_balance;
-- Deduct from locked balance (already deducted from available when request was made)
UPDATE user_internal_balances
SET
locked_balance = locked_balance - p_amount,
total_withdrawn = total_withdrawn + p_amount,
last_withdraw_at = NOW(),
updated_at = NOW()
WHERE user_id = p_user_id AND token = p_token;
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'withdraw', -p_amount,
v_locked_before, v_locked_before - p_amount, 'withdraw_request', p_request_id,
'Withdrawal completed. TX: ' || p_tx_hash
);
RETURN json_build_object(
'success', true,
'withdrawn_amount', p_amount,
'remaining_locked', v_locked_before - p_amount,
'tx_hash', p_tx_hash
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Grant execute to service role only (called from Edge Function)
REVOKE EXECUTE ON FUNCTION complete_withdraw FROM PUBLIC;
REVOKE EXECUTE ON FUNCTION complete_withdraw FROM authenticated;
REVOKE EXECUTE ON FUNCTION complete_withdraw FROM anon;
-- Create index for faster withdrawal request lookups
CREATE INDEX IF NOT EXISTS idx_withdraw_requests_pending
ON p2p_deposit_withdraw_requests(user_id, status)
WHERE request_type = 'withdraw' AND status = 'pending';
-- Add fee tracking columns if not exists
ALTER TABLE p2p_deposit_withdraw_requests
ADD COLUMN IF NOT EXISTS fee_amount DECIMAL(20, 12) DEFAULT 0;
ALTER TABLE p2p_deposit_withdraw_requests
ADD COLUMN IF NOT EXISTS net_amount DECIMAL(20, 12);
-- Trigger to calculate net amount
CREATE OR REPLACE FUNCTION calculate_withdraw_net_amount()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.request_type = 'withdraw' THEN
-- Default fees: HEZ = 0.1, PEZ = 1
IF NEW.fee_amount IS NULL OR NEW.fee_amount = 0 THEN
NEW.fee_amount := CASE NEW.token
WHEN 'HEZ' THEN 0.1
WHEN 'PEZ' THEN 1
ELSE 0
END;
END IF;
NEW.net_amount := NEW.amount - NEW.fee_amount;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trigger_calculate_withdraw_net ON p2p_deposit_withdraw_requests;
CREATE TRIGGER trigger_calculate_withdraw_net
BEFORE INSERT ON p2p_deposit_withdraw_requests
FOR EACH ROW EXECUTE FUNCTION calculate_withdraw_net_amount();
-- Add daily/monthly withdrawal limits table
CREATE TABLE IF NOT EXISTS p2p_withdrawal_limits (
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
daily_withdrawn DECIMAL(20, 12) DEFAULT 0,
monthly_withdrawn DECIMAL(20, 12) DEFAULT 0,
daily_limit DECIMAL(20, 12) DEFAULT 1000, -- Default 1000 HEZ/day
monthly_limit DECIMAL(20, 12) DEFAULT 10000, -- Default 10000 HEZ/month
last_daily_reset TIMESTAMPTZ DEFAULT NOW(),
last_monthly_reset TIMESTAMPTZ DEFAULT NOW(),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Function to check withdrawal limits
CREATE OR REPLACE FUNCTION check_withdrawal_limit(
p_user_id UUID,
p_amount DECIMAL(20, 12)
) RETURNS JSON AS $$
DECLARE
v_limits RECORD;
v_daily_remaining DECIMAL;
v_monthly_remaining DECIMAL;
BEGIN
-- Get or create limits record
INSERT INTO p2p_withdrawal_limits (user_id)
VALUES (p_user_id)
ON CONFLICT (user_id) DO NOTHING;
SELECT * INTO v_limits
FROM p2p_withdrawal_limits
WHERE user_id = p_user_id
FOR UPDATE;
-- Reset daily counter if needed
IF v_limits.last_daily_reset < CURRENT_DATE THEN
UPDATE p2p_withdrawal_limits
SET daily_withdrawn = 0, last_daily_reset = NOW()
WHERE user_id = p_user_id;
v_limits.daily_withdrawn := 0;
END IF;
-- Reset monthly counter if needed
IF v_limits.last_monthly_reset < DATE_TRUNC('month', CURRENT_DATE) THEN
UPDATE p2p_withdrawal_limits
SET monthly_withdrawn = 0, last_monthly_reset = NOW()
WHERE user_id = p_user_id;
v_limits.monthly_withdrawn := 0;
END IF;
v_daily_remaining := v_limits.daily_limit - v_limits.daily_withdrawn;
v_monthly_remaining := v_limits.monthly_limit - v_limits.monthly_withdrawn;
IF p_amount > v_daily_remaining THEN
RETURN json_build_object(
'allowed', false,
'error', format('Daily limit exceeded. Remaining: %s', v_daily_remaining),
'daily_remaining', v_daily_remaining,
'monthly_remaining', v_monthly_remaining
);
END IF;
IF p_amount > v_monthly_remaining THEN
RETURN json_build_object(
'allowed', false,
'error', format('Monthly limit exceeded. Remaining: %s', v_monthly_remaining),
'daily_remaining', v_daily_remaining,
'monthly_remaining', v_monthly_remaining
);
END IF;
RETURN json_build_object(
'allowed', true,
'daily_remaining', v_daily_remaining,
'monthly_remaining', v_monthly_remaining
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Function to record withdrawal in limits
CREATE OR REPLACE FUNCTION record_withdrawal_limit(
p_user_id UUID,
p_amount DECIMAL(20, 12)
) RETURNS void AS $$
BEGIN
UPDATE p2p_withdrawal_limits
SET
daily_withdrawn = daily_withdrawn + p_amount,
monthly_withdrawn = monthly_withdrawn + p_amount,
updated_at = NOW()
WHERE user_id = p_user_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION check_withdrawal_limit TO authenticated;
GRANT EXECUTE ON FUNCTION record_withdrawal_limit TO authenticated;
-- RLS for withdrawal limits
ALTER TABLE p2p_withdrawal_limits ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can view own withdrawal limits"
ON p2p_withdrawal_limits FOR SELECT
USING (user_id = auth.uid());
COMMENT ON FUNCTION complete_withdraw IS 'Completes a withdrawal after blockchain TX success. Service role only.';
COMMENT ON FUNCTION check_withdrawal_limit IS 'Check if user can withdraw the specified amount based on daily/monthly limits.';
@@ -0,0 +1,50 @@
-- =====================================================
-- Migration 018: Hot Wallet Configuration
-- Production hot wallet address setup
-- =====================================================
-- Update platform escrow balance with production hot wallet
UPDATE platform_escrow_balance
SET hot_wallet_address = '5HN6sFM7TbPQazmfhJP1kU8itw7Tb2A9UML8TwSYRwiN9q5Z'
WHERE token IN ('HEZ', 'PEZ');
-- Create hot wallet config table for additional metadata
CREATE TABLE IF NOT EXISTS platform_wallet_config (
id SERIAL PRIMARY KEY,
wallet_type TEXT NOT NULL CHECK (wallet_type IN ('hot', 'cold', 'fee_collector')),
wallet_address TEXT NOT NULL,
public_key TEXT,
description TEXT,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(wallet_type, wallet_address)
);
-- Insert hot wallet config
INSERT INTO platform_wallet_config (wallet_type, wallet_address, public_key, description)
VALUES (
'hot',
'5HN6sFM7TbPQazmfhJP1kU8itw7Tb2A9UML8TwSYRwiN9q5Z',
'0xea71cc341e6790988692d8adcd08a26c75d8c813e45e0a25b24b707dc7846677',
'P2P Platform Hot Wallet - Deposit/Withdraw operations'
)
ON CONFLICT (wallet_type, wallet_address) DO UPDATE SET
public_key = EXCLUDED.public_key,
description = EXCLUDED.description,
updated_at = NOW();
-- RLS: Only admins can view wallet config
ALTER TABLE platform_wallet_config ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Admin only wallet config"
ON platform_wallet_config FOR ALL
USING (
EXISTS (
SELECT 1 FROM profiles
WHERE id = auth.uid()
AND role IN ('admin', 'super_admin')
)
);
COMMENT ON TABLE platform_wallet_config IS 'Platform wallet addresses configuration. Private keys stored in Supabase Secrets.';
@@ -0,0 +1,61 @@
-- =====================================================
-- Migration 019: Admin Roles Setup
-- Assigns admin roles for P2P dispute resolution
-- =====================================================
-- Super Admin: satoshiqazi@gmail.com
-- Full access to all admin functions including dispute resolution
INSERT INTO public.admin_roles (user_id, role, granted_by)
SELECT
u.id,
'super_admin',
u.id
FROM auth.users u
WHERE u.email = 'satoshiqazi@gmail.com'
ON CONFLICT (user_id) DO UPDATE SET
role = 'super_admin',
updated_at = NOW();
-- Moderator: info@pezkuwichain.io
-- Can view and resolve disputes
INSERT INTO public.admin_roles (user_id, role, granted_by)
SELECT
u.id,
'moderator',
(SELECT id FROM auth.users WHERE email = 'satoshiqazi@gmail.com')
FROM auth.users u
WHERE u.email = 'info@pezkuwichain.io'
ON CONFLICT (user_id) DO UPDATE SET
role = 'moderator',
updated_at = NOW();
-- Verify the setup
DO $$
DECLARE
v_super_admin_count INT;
v_moderator_count INT;
BEGIN
SELECT COUNT(*) INTO v_super_admin_count
FROM admin_roles ar
JOIN auth.users u ON ar.user_id = u.id
WHERE u.email = 'satoshiqazi@gmail.com' AND ar.role = 'super_admin';
SELECT COUNT(*) INTO v_moderator_count
FROM admin_roles ar
JOIN auth.users u ON ar.user_id = u.id
WHERE u.email = 'info@pezkuwichain.io' AND ar.role = 'moderator';
IF v_super_admin_count = 1 THEN
RAISE NOTICE '✓ Super Admin assigned: satoshiqazi@gmail.com';
ELSE
RAISE WARNING '✗ Super Admin NOT found - user may not exist yet';
END IF;
IF v_moderator_count = 1 THEN
RAISE NOTICE '✓ Moderator assigned: info@pezkuwichain.io';
ELSE
RAISE WARNING '✗ Moderator NOT found - user may not exist yet';
END IF;
END $$;
COMMENT ON TABLE admin_roles IS 'Admin role assignments for P2P dispute resolution and platform management';
@@ -0,0 +1,398 @@
-- =====================================================
-- P2P Fiat Trading System
-- Production-grade schema with full security & audit
-- =====================================================
-- Enable required extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
-- =====================================================
-- PAYMENT METHODS TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.payment_methods (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
currency TEXT NOT NULL CHECK (currency IN ('TRY', 'IQD', 'IRR', 'EUR', 'USD')),
country TEXT NOT NULL,
method_name TEXT NOT NULL,
method_type TEXT NOT NULL CHECK (method_type IN ('bank', 'mobile_payment', 'cash', 'crypto_exchange')),
logo_url TEXT,
fields JSONB NOT NULL,
validation_rules JSONB DEFAULT '{}',
is_active BOOLEAN DEFAULT true,
display_order INT DEFAULT 0,
min_trade_amount NUMERIC DEFAULT 0,
max_trade_amount NUMERIC,
processing_time_minutes INT DEFAULT 60,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT unique_payment_method UNIQUE (currency, method_name)
);
CREATE INDEX IF NOT EXISTS idx_payment_methods_currency_active ON public.payment_methods(currency, is_active);
CREATE INDEX IF NOT EXISTS idx_payment_methods_type ON public.payment_methods(method_type);
-- =====================================================
-- P2P FIAT OFFERS TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_fiat_offers (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
seller_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
seller_wallet TEXT NOT NULL,
-- Crypto side
token TEXT NOT NULL CHECK (token IN ('HEZ', 'PEZ')),
amount_crypto NUMERIC NOT NULL CHECK (amount_crypto > 0),
-- Fiat side
fiat_currency TEXT NOT NULL CHECK (fiat_currency IN ('TRY', 'IQD', 'IRR', 'EUR', 'USD')),
fiat_amount NUMERIC NOT NULL CHECK (fiat_amount > 0),
price_per_unit NUMERIC GENERATED ALWAYS AS (fiat_amount / amount_crypto) STORED,
-- Payment details
payment_method_id UUID NOT NULL REFERENCES public.payment_methods(id),
payment_details_encrypted TEXT NOT NULL, -- PGP encrypted JSONB
-- Terms
min_order_amount NUMERIC CHECK (min_order_amount > 0 AND min_order_amount <= amount_crypto),
max_order_amount NUMERIC CHECK (max_order_amount >= min_order_amount AND max_order_amount <= amount_crypto),
time_limit_minutes INT DEFAULT 30 CHECK (time_limit_minutes BETWEEN 15 AND 120),
auto_reply_message TEXT,
-- Restrictions
min_buyer_completed_trades INT DEFAULT 0,
min_buyer_reputation INT DEFAULT 0,
blocked_users UUID[] DEFAULT '{}',
-- Status
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'paused', 'locked', 'completed', 'cancelled')),
remaining_amount NUMERIC NOT NULL CHECK (remaining_amount >= 0 AND remaining_amount <= amount_crypto),
-- Escrow tracking
escrow_tx_hash TEXT,
escrow_locked_at TIMESTAMPTZ,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
expires_at TIMESTAMPTZ DEFAULT NOW() + INTERVAL '7 days',
CONSTRAINT check_order_amounts CHECK (
(min_order_amount IS NULL AND max_order_amount IS NULL) OR
(min_order_amount IS NOT NULL AND max_order_amount IS NOT NULL)
)
);
CREATE INDEX IF NOT EXISTS idx_p2p_offers_seller ON public.p2p_fiat_offers(seller_id);
CREATE INDEX IF NOT EXISTS idx_p2p_offers_currency ON public.p2p_fiat_offers(fiat_currency, token);
CREATE INDEX IF NOT EXISTS idx_p2p_offers_status ON public.p2p_fiat_offers(status)WHERE status IN ('open', 'paused');
CREATE INDEX IF NOT EXISTS idx_p2p_offers_active ON public.p2p_fiat_offers(status, fiat_currency, token)
WHERE status = 'open' AND remaining_amount > 0;
-- =====================================================
-- P2P FIAT TRADES TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_fiat_trades (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
offer_id UUID NOT NULL REFERENCES public.p2p_fiat_offers(id) ON DELETE CASCADE,
seller_id UUID NOT NULL REFERENCES auth.users(id),
buyer_id UUID NOT NULL REFERENCES auth.users(id),
buyer_wallet TEXT NOT NULL,
-- Trade amounts
crypto_amount NUMERIC NOT NULL CHECK (crypto_amount > 0),
fiat_amount NUMERIC NOT NULL CHECK (fiat_amount > 0),
price_per_unit NUMERIC NOT NULL,
-- Escrow
escrow_locked_amount NUMERIC NOT NULL,
escrow_locked_at TIMESTAMPTZ,
escrow_release_tx_hash TEXT,
escrow_released_at TIMESTAMPTZ,
-- Payment tracking
buyer_marked_paid_at TIMESTAMPTZ,
buyer_payment_proof_url TEXT, -- IPFS hash
seller_confirmed_at TIMESTAMPTZ,
-- Chat messages (encrypted)
chat_messages JSONB DEFAULT '[]',
-- Status
status TEXT NOT NULL DEFAULT 'pending' CHECK (
status IN ('pending', 'payment_sent', 'completed', 'cancelled', 'disputed', 'refunded')
),
-- Deadlines
payment_deadline TIMESTAMPTZ NOT NULL,
confirmation_deadline TIMESTAMPTZ,
-- Cancellation/Dispute
cancelled_by UUID REFERENCES auth.users(id),
cancellation_reason TEXT,
dispute_id UUID,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
completed_at TIMESTAMPTZ,
CONSTRAINT different_users CHECK (seller_id != buyer_id)
);
CREATE INDEX IF NOT EXISTS idx_p2p_trades_offer ON public.p2p_fiat_trades(offer_id);
CREATE INDEX IF NOT EXISTS idx_p2p_trades_seller ON public.p2p_fiat_trades(seller_id);
CREATE INDEX IF NOT EXISTS idx_p2p_trades_buyer ON public.p2p_fiat_trades(buyer_id);
CREATE INDEX IF NOT EXISTS idx_p2p_trades_status ON public.p2p_fiat_trades(status);
CREATE INDEX IF NOT EXISTS idx_p2p_trades_deadlines ON public.p2p_fiat_trades(payment_deadline, confirmation_deadline)
WHERE status IN ('pending', 'payment_sent');
-- =====================================================
-- P2P DISPUTES TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_fiat_disputes (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
trade_id UUID NOT NULL REFERENCES public.p2p_fiat_trades(id) ON DELETE CASCADE,
opened_by UUID NOT NULL REFERENCES auth.users(id),
-- Dispute details
reason TEXT NOT NULL CHECK (LENGTH(reason) >= 20),
category TEXT NOT NULL CHECK (
category IN ('payment_not_received', 'wrong_amount', 'fake_payment_proof', 'other')
),
evidence_urls TEXT[] DEFAULT '{}', -- IPFS hashes
additional_info JSONB DEFAULT '{}',
-- Moderator assignment
assigned_moderator_id UUID REFERENCES auth.users(id),
assigned_at TIMESTAMPTZ,
-- Resolution
decision TEXT CHECK (decision IN ('release_to_buyer', 'refund_to_seller', 'split', 'escalate')),
decision_reasoning TEXT,
resolved_at TIMESTAMPTZ,
-- Status
status TEXT NOT NULL DEFAULT 'open' CHECK (
status IN ('open', 'under_review', 'resolved', 'escalated', 'closed')
),
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT one_dispute_per_trade UNIQUE (trade_id)
);
CREATE INDEX IF NOT EXISTS idx_disputes_trade ON public.p2p_fiat_disputes(trade_id);
CREATE INDEX IF NOT EXISTS idx_disputes_status ON public.p2p_fiat_disputes(status)WHERE status IN ('open', 'under_review');
CREATE INDEX IF NOT EXISTS idx_disputes_moderator ON public.p2p_fiat_disputes(assigned_moderator_id) WHERE status = 'under_review';
-- =====================================================
-- P2P REPUTATION TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_reputation (
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
-- Trade statistics
total_trades INT DEFAULT 0 CHECK (total_trades >= 0),
completed_trades INT DEFAULT 0 CHECK (completed_trades >= 0 AND completed_trades <= total_trades),
cancelled_trades INT DEFAULT 0 CHECK (cancelled_trades >= 0),
disputed_trades INT DEFAULT 0 CHECK (disputed_trades >= 0),
-- Role statistics
total_as_seller INT DEFAULT 0 CHECK (total_as_seller >= 0),
total_as_buyer INT DEFAULT 0 CHECK (total_as_buyer >= 0),
-- Volume
total_volume_usd NUMERIC DEFAULT 0 CHECK (total_volume_usd >= 0),
-- Timing metrics
avg_payment_time_minutes INT,
avg_confirmation_time_minutes INT,
-- Reputation score (0-1000)
reputation_score INT DEFAULT 100 CHECK (reputation_score BETWEEN 0 AND 1000),
trust_level TEXT DEFAULT 'new' CHECK (
trust_level IN ('new', 'basic', 'intermediate', 'advanced', 'verified')
),
-- Badges
verified_merchant BOOLEAN DEFAULT false,
fast_trader BOOLEAN DEFAULT false,
-- Restrictions
is_restricted BOOLEAN DEFAULT false,
restriction_reason TEXT,
restricted_until TIMESTAMPTZ,
-- Timestamps
first_trade_at TIMESTAMPTZ,
last_trade_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_reputation_score ON public.p2p_reputation(reputation_score DESC);
CREATE INDEX IF NOT EXISTS idx_reputation_verified ON public.p2p_reputation(verified_merchant) WHERE verified_merchant = true;
-- =====================================================
-- PLATFORM ESCROW TRACKING
-- =====================================================
CREATE TABLE IF NOT EXISTS public.platform_escrow_balance (
token TEXT PRIMARY KEY CHECK (token IN ('HEZ', 'PEZ')),
total_locked NUMERIC DEFAULT 0 CHECK (total_locked >= 0),
hot_wallet_address TEXT NOT NULL,
last_audit_at TIMESTAMPTZ,
last_audit_blockchain_balance NUMERIC,
discrepancy NUMERIC GENERATED ALWAYS AS (last_audit_blockchain_balance - total_locked) STORED,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- =====================================================
-- AUDIT LOG
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_audit_log (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES auth.users(id),
action TEXT NOT NULL,
entity_type TEXT NOT NULL CHECK (entity_type IN ('offer', 'trade', 'dispute')),
entity_id UUID NOT NULL,
details JSONB DEFAULT '{}',
ip_address INET,
user_agent TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_audit_log_user ON public.p2p_audit_log(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_entity ON public.p2p_audit_log(entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON public.p2p_audit_log(created_at DESC);
-- =====================================================
-- TRIGGERS FOR UPDATED_AT
-- =====================================================
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS update_payment_methods_updated_at ON public.payment_methods;
CREATE TRIGGER update_payment_methods_updated_at BEFORE UPDATE ON public.payment_methods
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
DROP TRIGGER IF EXISTS update_p2p_offers_updated_at ON public.p2p_fiat_offers;
CREATE TRIGGER update_p2p_offers_updated_at BEFORE UPDATE ON public.p2p_fiat_offers
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
DROP TRIGGER IF EXISTS update_p2p_trades_updated_at ON public.p2p_fiat_trades;
CREATE TRIGGER update_p2p_trades_updated_at BEFORE UPDATE ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
DROP TRIGGER IF EXISTS update_p2p_disputes_updated_at ON public.p2p_fiat_disputes;
CREATE TRIGGER update_p2p_disputes_updated_at BEFORE UPDATE ON public.p2p_fiat_disputes
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-- =====================================================
-- RLS POLICIES
-- =====================================================
-- Payment Methods: Public read
ALTER TABLE public.payment_methods ENABLE ROW LEVEL SECURITY;
CREATE POLICY "payment_methods_public_read" ON public.payment_methods
FOR SELECT USING (is_active = true);
CREATE POLICY "payment_methods_admin_all" ON public.payment_methods
FOR ALL USING (
EXISTS (SELECT 1 FROM public.admin_roles WHERE user_id = auth.uid())
);
-- P2P Offers: Public read active, sellers manage own
ALTER TABLE public.p2p_fiat_offers ENABLE ROW LEVEL SECURITY;
CREATE POLICY "offers_public_read_active" ON public.p2p_fiat_offers
FOR SELECT USING (
status IN ('open', 'paused') AND
remaining_amount > 0 AND
expires_at > NOW()
);
CREATE POLICY "offers_seller_read_own" ON public.p2p_fiat_offers
FOR SELECT USING (seller_id = auth.uid());
CREATE POLICY "offers_seller_insert" ON public.p2p_fiat_offers
FOR INSERT WITH CHECK (seller_id = auth.uid());
CREATE POLICY "offers_seller_update_own" ON public.p2p_fiat_offers
FOR UPDATE USING (seller_id = auth.uid());
CREATE POLICY "offers_seller_delete_own" ON public.p2p_fiat_offers
FOR DELETE USING (seller_id = auth.uid() AND status IN ('open', 'paused'));
-- P2P Trades: Parties can view/update own trades
ALTER TABLE public.p2p_fiat_trades ENABLE ROW LEVEL SECURITY;
CREATE POLICY "trades_parties_read" ON public.p2p_fiat_trades
FOR SELECT USING (seller_id = auth.uid() OR buyer_id = auth.uid());
CREATE POLICY "trades_buyer_insert" ON public.p2p_fiat_trades
FOR INSERT WITH CHECK (buyer_id = auth.uid());
CREATE POLICY "trades_parties_update" ON public.p2p_fiat_trades
FOR UPDATE USING (seller_id = auth.uid() OR buyer_id = auth.uid());
-- Disputes: Parties and moderators
ALTER TABLE public.p2p_fiat_disputes ENABLE ROW LEVEL SECURITY;
CREATE POLICY "disputes_parties_read" ON public.p2p_fiat_disputes
FOR SELECT USING (
opened_by = auth.uid() OR
EXISTS (
SELECT 1 FROM public.p2p_fiat_trades t
WHERE t.id = trade_id AND (t.seller_id = auth.uid() OR t.buyer_id = auth.uid())
)
);
CREATE POLICY "disputes_moderators_read" ON public.p2p_fiat_disputes
FOR SELECT USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
CREATE POLICY "disputes_parties_insert" ON public.p2p_fiat_disputes
FOR INSERT WITH CHECK (
opened_by = auth.uid() AND
EXISTS (
SELECT 1 FROM public.p2p_fiat_trades t
WHERE t.id = trade_id AND (t.seller_id = auth.uid() OR t.buyer_id = auth.uid())
)
);
-- Reputation: Public read, system updates
ALTER TABLE public.p2p_reputation ENABLE ROW LEVEL SECURITY;
CREATE POLICY "reputation_public_read" ON public.p2p_reputation
FOR SELECT USING (true);
-- Escrow: Admin only
ALTER TABLE public.platform_escrow_balance ENABLE ROW LEVEL SECURITY;
CREATE POLICY "escrow_admin_only" ON public.platform_escrow_balance
FOR ALL USING (
EXISTS (SELECT 1 FROM public.admin_roles WHERE user_id = auth.uid())
);
-- Audit log: Own + admins
ALTER TABLE public.p2p_audit_log ENABLE ROW LEVEL SECURITY;
CREATE POLICY "audit_user_read_own" ON public.p2p_audit_log
FOR SELECT USING (user_id = auth.uid());
CREATE POLICY "audit_admin_read_all" ON public.p2p_audit_log
FOR SELECT USING (
EXISTS (SELECT 1 FROM public.admin_roles WHERE user_id = auth.uid())
);
@@ -0,0 +1,250 @@
-- =====================================================
-- PAYMENT METHODS DATA - PRODUCTION
-- =====================================================
INSERT INTO public.payment_methods (currency, country, method_name, method_type, fields, validation_rules, min_trade_amount, max_trade_amount, processing_time_minutes, display_order) VALUES
-- ========== TURKEY (TRY) ==========
('TRY', 'TR', 'Ziraat Bankası', 'bank',
'{"iban": "", "account_holder": "", "branch_code": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 1),
('TRY', 'TR', 'İş Bankası', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 2),
('TRY', 'TR', 'Garanti BBVA', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 3),
('TRY', 'TR', 'Yapı Kredi', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 4),
('TRY', 'TR', 'Akbank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 5),
('TRY', 'TR', 'Halkbank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 6),
('TRY', 'TR', 'Vakıfbank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 7),
('TRY', 'TR', 'QNB Finansbank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 8),
('TRY', 'TR', 'TEB', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 9),
('TRY', 'TR', 'Denizbank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 30, 10),
('TRY', 'TR', 'Papara', 'mobile_payment',
'{"papara_number": "", "full_name": ""}',
'{"papara_number": {"pattern": "^[0-9]{10}$", "required": true}}',
50, 50000, 5, 11),
('TRY', 'TR', 'Paybol', 'mobile_payment',
'{"phone_number": "", "full_name": ""}',
'{"phone_number": {"pattern": "^\\+90[0-9]{10}$", "required": true}}',
50, 50000, 10, 12),
('TRY', 'TR', 'FAST (Hızlı Transfer)', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^TR[0-9]{24}$", "required": true}}',
100, 100000, 15, 13),
-- ========== IRAQ (IQD) ==========
('IQD', 'IQ', 'Rasheed Bank', 'bank',
'{"account_number": "", "account_holder": "", "branch": ""}',
'{"account_number": {"minLength": 10, "required": true}}',
50000, 50000000, 60, 1),
('IQD', 'IQ', 'Rafidain Bank', 'bank',
'{"account_number": "", "account_holder": "", "branch": ""}',
'{"account_number": {"minLength": 10, "required": true}}',
50000, 50000000, 60, 2),
('IQD', 'IQ', 'Trade Bank of Iraq (TBI)', 'bank',
'{"account_number": "", "account_holder": "", "swift_code": ""}',
'{"account_number": {"minLength": 10, "required": true}}',
50000, 50000000, 60, 3),
('IQD', 'IQ', 'Kurdistan International Bank', 'bank',
'{"account_number": "", "account_holder": "", "branch": ""}',
'{"account_number": {"minLength": 10, "required": true}}',
50000, 50000000, 60, 4),
('IQD', 'IQ', 'Cihan Bank', 'bank',
'{"account_number": "", "account_holder": ""}',
'{"account_number": {"minLength": 10, "required": true}}',
50000, 50000000, 60, 5),
('IQD', 'IQ', 'Fast Pay', 'mobile_payment',
'{"fast_pay_id": "", "phone_number": "", "full_name": ""}',
'{"fast_pay_id": {"minLength": 6, "required": true}}',
10000, 20000000, 15, 6),
('IQD', 'IQ', 'Zain Cash', 'mobile_payment',
'{"zain_number": "", "full_name": ""}',
'{"zain_number": {"pattern": "^07[0-9]{9}$", "required": true}}',
10000, 20000000, 15, 7),
('IQD', 'IQ', 'Asia Hawala', 'mobile_payment',
'{"hawala_code": "", "phone_number": "", "full_name": ""}',
'{"hawala_code": {"minLength": 8, "required": true}}',
50000, 30000000, 30, 8),
('IQD', 'IQ', 'Korek Money Transfer', 'mobile_payment',
'{"korek_number": "", "full_name": ""}',
'{"korek_number": {"pattern": "^04[0-9]{8}$", "required": true}}',
10000, 20000000, 15, 9),
('IQD', 'IQ', 'Qi Card', 'mobile_payment',
'{"qi_card_number": "", "full_name": ""}',
'{"qi_card_number": {"minLength": 16, "maxLength": 19, "required": true}}',
10000, 20000000, 15, 10),
-- ========== IRAN (IRR) ==========
('IRR', 'IR', 'Bank Mellat', 'bank',
'{"card_number": "", "account_holder": "", "sheba": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 500000000, 60, 1),
('IRR', 'IR', 'Bank Melli Iran', 'bank',
'{"card_number": "", "account_holder": "", "sheba": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 500000000, 60, 2),
('IRR', 'IR', 'Bank Saderat', 'bank',
'{"card_number": "", "account_holder": "", "sheba": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 500000000, 60, 3),
('IRR', 'IR', 'Bank Tejarat', 'bank',
'{"card_number": "", "account_holder": "", "sheba": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 500000000, 60, 4),
('IRR', 'IR', 'Pasargad Bank', 'bank',
'{"card_number": "", "account_holder": "", "sheba": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 500000000, 60, 5),
('IRR', 'IR', 'Bank Keshavarzi', 'bank',
'{"card_number": "", "account_holder": "", "sheba": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
1000000, 500000000, 60, 6),
('IRR', 'IR', 'Shetab Card Transfer', 'mobile_payment',
'{"card_number": "", "full_name": ""}',
'{"card_number": {"pattern": "^[0-9]{16}$", "required": true}}',
500000, 300000000, 10, 7),
-- ========== EUROPE (EUR) ==========
('EUR', 'EU', 'SEPA Bank Transfer', 'bank',
'{"iban": "", "bic_swift": "", "account_holder": "", "bank_name": ""}',
'{"iban": {"pattern": "^[A-Z]{2}[0-9]{2}[A-Z0-9]+$", "required": true}}',
50, 50000, 120, 1),
('EUR', 'EU', 'Wise (TransferWise)', 'mobile_payment',
'{"wise_email": "", "full_name": ""}',
'{"wise_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
20, 20000, 30, 2),
('EUR', 'EU', 'Revolut', 'mobile_payment',
'{"revolut_tag": "", "full_name": ""}',
'{"revolut_tag": {"pattern": "^@[a-zA-Z0-9_]+$", "required": true}}',
20, 20000, 15, 3),
('EUR', 'EU', 'N26', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
50, 50000, 60, 4),
('EUR', 'EU', 'PayPal', 'mobile_payment',
'{"paypal_email": ""}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 10000, 30, 5),
('EUR', 'DE', 'Deutsche Bank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^DE[0-9]{20}$", "required": true}}',
50, 50000, 60, 6),
('EUR', 'FR', 'BNP Paribas', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^FR[0-9]{25}$", "required": true}}',
50, 50000, 60, 7),
('EUR', 'NL', 'ING Bank', 'bank',
'{"iban": "", "account_holder": ""}',
'{"iban": {"pattern": "^NL[0-9]{16}$", "required": true}}',
50, 50000, 60, 8),
-- ========== UNITED STATES (USD) ==========
('USD', 'US', 'Bank of America', 'bank',
'{"account_number": "", "routing_number": "", "account_holder": "", "account_type": ""}',
'{"account_number": {"minLength": 8, "required": true}, "routing_number": {"pattern": "^[0-9]{9}$", "required": true}}',
100, 50000, 180, 1),
('USD', 'US', 'Chase Bank', 'bank',
'{"account_number": "", "routing_number": "", "account_holder": ""}',
'{"account_number": {"minLength": 8, "required": true}, "routing_number": {"pattern": "^[0-9]{9}$", "required": true}}',
100, 50000, 180, 2),
('USD', 'US', 'Wells Fargo', 'bank',
'{"account_number": "", "routing_number": "", "account_holder": ""}',
'{"account_number": {"minLength": 8, "required": true}, "routing_number": {"pattern": "^[0-9]{9}$", "required": true}}',
100, 50000, 180, 3),
('USD', 'US', 'Zelle', 'mobile_payment',
'{"zelle_email_or_phone": "", "full_name": ""}',
'{"zelle_email_or_phone": {"minLength": 5, "required": true}}',
50, 20000, 15, 4),
('USD', 'US', 'Venmo', 'mobile_payment',
'{"venmo_username": "", "full_name": ""}',
'{"venmo_username": {"pattern": "^@[a-zA-Z0-9_-]+$", "required": true}}',
10, 5000, 15, 5),
('USD', 'US', 'Cash App', 'mobile_payment',
'{"cashtag": "", "full_name": ""}',
'{"cashtag": {"pattern": "^\\$[a-zA-Z0-9]+$", "required": true}}',
10, 5000, 15, 6),
('USD', 'US', 'PayPal', 'mobile_payment',
'{"paypal_email": ""}',
'{"paypal_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
10, 10000, 30, 7),
('USD', 'US', 'Wise (USD)', 'mobile_payment',
'{"wise_email": "", "full_name": ""}',
'{"wise_email": {"pattern": "^[^@]+@[^@]+\\.[^@]+$", "required": true}}',
20, 20000, 30, 8),
('USD', 'US', 'Western Union', 'cash',
'{"mtcn": "", "receiver_name": "", "receiver_country": ""}',
'{"mtcn": {"pattern": "^[0-9]{10}$", "required": true}}',
50, 10000, 60, 9);
-- Initialize escrow balance
INSERT INTO public.platform_escrow_balance (token, total_locked, hot_wallet_address, last_audit_at) VALUES
('HEZ', 0, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', NOW()),
('PEZ', 0, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', NOW());
@@ -0,0 +1,310 @@
-- =====================================================
-- P2P FIAT SYSTEM - RPC FUNCTIONS
-- Production-grade stored procedures
-- =====================================================
-- =====================================================
-- INCREMENT ESCROW BALANCE
-- =====================================================
CREATE OR REPLACE FUNCTION public.increment_escrow_balance(
p_token TEXT,
p_amount NUMERIC
) RETURNS void AS $$
BEGIN
UPDATE public.platform_escrow_balance
SET
total_locked = total_locked + p_amount,
updated_at = NOW()
WHERE token = p_token;
IF NOT FOUND THEN
RAISE EXCEPTION 'Token % not found in escrow balance', p_token;
END IF;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- DECREMENT ESCROW BALANCE
-- =====================================================
CREATE OR REPLACE FUNCTION public.decrement_escrow_balance(
p_token TEXT,
p_amount NUMERIC
) RETURNS void AS $$
BEGIN
UPDATE public.platform_escrow_balance
SET
total_locked = total_locked - p_amount,
updated_at = NOW()
WHERE token = p_token;
IF NOT FOUND THEN
RAISE EXCEPTION 'Token % not found in escrow balance', p_token;
END IF;
-- Check for negative balance (should never happen)
IF (SELECT total_locked FROM public.platform_escrow_balance WHERE token = p_token) < 0 THEN
RAISE EXCEPTION 'Escrow balance would go negative for token %', p_token;
END IF;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- UPDATE P2P REPUTATION AFTER TRADE
-- =====================================================
CREATE OR REPLACE FUNCTION public.update_p2p_reputation(
p_seller_id UUID,
p_buyer_id UUID,
p_trade_id UUID
) RETURNS void AS $$
DECLARE
v_trade RECORD;
v_payment_time_minutes INT;
v_confirmation_time_minutes INT;
BEGIN
-- Get trade details
SELECT * INTO v_trade
FROM public.p2p_fiat_trades
WHERE id = p_trade_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'Trade % not found', p_trade_id;
END IF;
-- Calculate timing metrics
IF v_trade.buyer_marked_paid_at IS NOT NULL THEN
v_payment_time_minutes := EXTRACT(EPOCH FROM (v_trade.buyer_marked_paid_at - v_trade.created_at)) / 60;
END IF;
IF v_trade.seller_confirmed_at IS NOT NULL AND v_trade.buyer_marked_paid_at IS NOT NULL THEN
v_confirmation_time_minutes := EXTRACT(EPOCH FROM (v_trade.seller_confirmed_at - v_trade.buyer_marked_paid_at)) / 60;
END IF;
-- Update seller reputation
INSERT INTO public.p2p_reputation (
user_id,
total_trades,
completed_trades,
total_as_seller,
reputation_score,
avg_confirmation_time_minutes,
last_trade_at,
first_trade_at
) VALUES (
p_seller_id,
1,
1,
1,
105, -- +5 bonus for first trade
v_confirmation_time_minutes,
NOW(),
NOW()
)
ON CONFLICT (user_id) DO UPDATE SET
total_trades = p2p_reputation.total_trades + 1,
completed_trades = p2p_reputation.completed_trades + 1,
total_as_seller = p2p_reputation.total_as_seller + 1,
reputation_score = LEAST(p2p_reputation.reputation_score + 5, 1000),
avg_confirmation_time_minutes = CASE
WHEN p2p_reputation.avg_confirmation_time_minutes IS NULL THEN v_confirmation_time_minutes
ELSE (p2p_reputation.avg_confirmation_time_minutes + COALESCE(v_confirmation_time_minutes, 0)) / 2
END,
last_trade_at = NOW(),
updated_at = NOW();
-- Update buyer reputation
INSERT INTO public.p2p_reputation (
user_id,
total_trades,
completed_trades,
total_as_buyer,
reputation_score,
avg_payment_time_minutes,
last_trade_at,
first_trade_at
) VALUES (
p_buyer_id,
1,
1,
1,
105,
v_payment_time_minutes,
NOW(),
NOW()
)
ON CONFLICT (user_id) DO UPDATE SET
total_trades = p2p_reputation.total_trades + 1,
completed_trades = p2p_reputation.completed_trades + 1,
total_as_buyer = p2p_reputation.total_as_buyer + 1,
reputation_score = LEAST(p2p_reputation.reputation_score + 5, 1000),
avg_payment_time_minutes = CASE
WHEN p2p_reputation.avg_payment_time_minutes IS NULL THEN v_payment_time_minutes
ELSE (p2p_reputation.avg_payment_time_minutes + COALESCE(v_payment_time_minutes, 0)) / 2
END,
last_trade_at = NOW(),
updated_at = NOW();
-- Update trust levels based on reputation score
UPDATE public.p2p_reputation
SET trust_level = CASE
WHEN reputation_score >= 900 THEN 'verified'
WHEN reputation_score >= 700 THEN 'advanced'
WHEN reputation_score >= 400 THEN 'intermediate'
WHEN reputation_score >= 100 THEN 'basic'
ELSE 'new'
END,
fast_trader = CASE
WHEN avg_payment_time_minutes < 15 AND avg_confirmation_time_minutes < 30 THEN true
ELSE false
END
WHERE user_id IN (p_seller_id, p_buyer_id);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- CANCEL EXPIRED TRADES (Cron job function)
-- =====================================================
CREATE OR REPLACE FUNCTION public.cancel_expired_trades()
RETURNS void AS $$
DECLARE
v_trade RECORD;
BEGIN
-- Cancel trades where buyer didn't pay in time
FOR v_trade IN
SELECT * FROM public.p2p_fiat_trades
WHERE status = 'pending'
AND payment_deadline < NOW()
LOOP
-- Update trade status
UPDATE public.p2p_fiat_trades
SET
status = 'cancelled',
cancelled_by = seller_id,
cancellation_reason = 'Payment deadline expired',
updated_at = NOW()
WHERE id = v_trade.id;
-- Restore offer remaining amount
UPDATE public.p2p_fiat_offers
SET
remaining_amount = remaining_amount + v_trade.crypto_amount,
status = CASE
WHEN status = 'locked' THEN 'open'
ELSE status
END,
updated_at = NOW()
WHERE id = v_trade.offer_id;
-- Update reputation (penalty for buyer)
UPDATE public.p2p_reputation
SET
cancelled_trades = cancelled_trades + 1,
reputation_score = GREATEST(reputation_score - 10, 0),
updated_at = NOW()
WHERE user_id = v_trade.buyer_id;
END LOOP;
-- Auto-release trades where seller didn't confirm in time
FOR v_trade IN
SELECT * FROM public.p2p_fiat_trades
WHERE status = 'payment_sent'
AND confirmation_deadline < NOW()
LOOP
-- Mark as completed (auto-release)
UPDATE public.p2p_fiat_trades
SET
seller_confirmed_at = NOW(),
status = 'completed',
completed_at = NOW(),
updated_at = NOW()
WHERE id = v_trade.id;
-- Note: Actual blockchain release must be done by backend service
-- This just marks the trade as ready for release
-- Update reputations
PERFORM public.update_p2p_reputation(v_trade.seller_id, v_trade.buyer_id, v_trade.id);
END LOOP;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- CANCEL EXPIRED OFFERS
-- =====================================================
CREATE OR REPLACE FUNCTION public.cancel_expired_offers()
RETURNS void AS $$
BEGIN
UPDATE public.p2p_fiat_offers
SET
status = 'cancelled',
updated_at = NOW()
WHERE status = 'open'
AND expires_at < NOW();
-- Note: Escrow refunds must be processed by backend service
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- GET PAYMENT METHOD DETAILS
-- =====================================================
CREATE OR REPLACE FUNCTION public.get_payment_method_details(
p_offer_id UUID,
p_requesting_user_id UUID
) RETURNS TABLE(
method_name TEXT,
payment_details JSONB
) AS $$
DECLARE
v_offer RECORD;
v_trade RECORD;
BEGIN
-- Get offer
SELECT * INTO v_offer
FROM public.p2p_fiat_offers
WHERE id = p_offer_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'Offer not found';
END IF;
-- Check if user is involved in an active trade for this offer
SELECT * INTO v_trade
FROM public.p2p_fiat_trades
WHERE offer_id = p_offer_id
AND buyer_id = p_requesting_user_id
AND status IN ('pending', 'payment_sent')
LIMIT 1;
IF NOT FOUND THEN
RAISE EXCEPTION 'Unauthorized: You must have an active trade to view payment details';
END IF;
-- Return decrypted payment details
RETURN QUERY
SELECT
pm.method_name,
CASE
WHEN v_offer.payment_details_encrypted IS NOT NULL THEN
pgsodium.crypto_aead_aes256gcm_decrypt(
pgsodium.url_decode((v_offer.payment_details_encrypted->>'ciphertext')::TEXT),
NULL, -- No associated data used in this context
pgsodium.url_decode((v_offer.payment_details_encrypted->>'nonce')::TEXT),
pg_catalog.get_secret_variable('app.app_encryption_key')::BYTEA
)::TEXT::JSONB
ELSE
NULL
END AS payment_details
FROM public.payment_methods pm
WHERE pm.id = v_offer.payment_method_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- GRANT EXECUTE PERMISSIONS
-- =====================================================
GRANT EXECUTE ON FUNCTION public.increment_escrow_balance TO authenticated;
GRANT EXECUTE ON FUNCTION public.decrement_escrow_balance TO authenticated;
GRANT EXECUTE ON FUNCTION public.update_p2p_reputation TO authenticated;
GRANT EXECUTE ON FUNCTION public.cancel_expired_trades TO authenticated;
GRANT EXECUTE ON FUNCTION public.cancel_expired_offers TO authenticated;
GRANT EXECUTE ON FUNCTION public.get_payment_method_details TO authenticated;
@@ -0,0 +1,566 @@
-- =====================================================
-- P2P FIAT SYSTEM - PHASE 2 & 3 ADDITIONAL TABLES
-- Messages, Ratings, Notifications, Evidence, Fraud Reports
-- =====================================================
-- =====================================================
-- P2P MESSAGES TABLE (Phase 2 - Chat System)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
trade_id UUID NOT NULL REFERENCES public.p2p_fiat_trades(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES auth.users(id),
-- Message content
message TEXT NOT NULL CHECK (LENGTH(message) > 0 AND LENGTH(message) <= 2000),
message_type VARCHAR(20) DEFAULT 'text' CHECK (message_type IN ('text', 'image', 'system')),
attachment_url TEXT, -- Supabase Storage URL
-- Read status
is_read BOOLEAN DEFAULT FALSE,
read_at TIMESTAMPTZ,
-- Metadata
metadata JSONB DEFAULT '{}',
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes for p2p_messages
CREATE INDEX idx_p2p_messages_trade ON public.p2p_messages(trade_id, created_at DESC);
CREATE INDEX idx_p2p_messages_sender ON public.p2p_messages(sender_id);
CREATE INDEX idx_p2p_messages_unread ON public.p2p_messages(trade_id, is_read) WHERE is_read = false;
-- Enable RLS
ALTER TABLE public.p2p_messages ENABLE ROW LEVEL SECURITY;
-- Policy: Only trade participants can read/write messages
CREATE POLICY "p2p_messages_trade_participants" ON public.p2p_messages
FOR ALL USING (
EXISTS (
SELECT 1 FROM public.p2p_fiat_trades t
WHERE t.id = trade_id
AND (t.seller_id = auth.uid() OR t.buyer_id = auth.uid())
)
);
-- =====================================================
-- P2P RATINGS TABLE (Phase 2 - Trust System)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_ratings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
trade_id UUID NOT NULL REFERENCES public.p2p_fiat_trades(id) ON DELETE CASCADE,
rater_id UUID NOT NULL REFERENCES auth.users(id),
rated_id UUID NOT NULL REFERENCES auth.users(id),
-- Rating details
rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
review TEXT CHECK (LENGTH(review) <= 500),
-- Rating aspects (optional breakdown)
communication_rating INT CHECK (communication_rating BETWEEN 1 AND 5),
speed_rating INT CHECK (speed_rating BETWEEN 1 AND 5),
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
-- Constraints
CONSTRAINT unique_rating_per_trade UNIQUE(trade_id, rater_id),
CONSTRAINT cannot_rate_self CHECK (rater_id != rated_id)
);
-- Indexes for p2p_ratings
CREATE INDEX idx_p2p_ratings_trade ON public.p2p_ratings(trade_id);
CREATE INDEX idx_p2p_ratings_rated ON public.p2p_ratings(rated_id, created_at DESC);
CREATE INDEX idx_p2p_ratings_rater ON public.p2p_ratings(rater_id);
-- Enable RLS
ALTER TABLE public.p2p_ratings ENABLE ROW LEVEL SECURITY;
-- Policy: Public read (for reputation display)
CREATE POLICY "p2p_ratings_public_read" ON public.p2p_ratings
FOR SELECT USING (true);
-- Policy: Only trade participants can insert ratings
CREATE POLICY "p2p_ratings_trade_participants_insert" ON public.p2p_ratings
FOR INSERT WITH CHECK (
rater_id = auth.uid() AND
EXISTS (
SELECT 1 FROM public.p2p_fiat_trades t
WHERE t.id = trade_id
AND t.status = 'completed'
AND (t.seller_id = auth.uid() OR t.buyer_id = auth.uid())
)
);
-- =====================================================
-- P2P NOTIFICATIONS TABLE (Phase 2 - Real-time Alerts)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
-- Notification content
type VARCHAR(50) NOT NULL CHECK (type IN (
'new_order', 'payment_sent', 'payment_confirmed', 'trade_cancelled',
'dispute_opened', 'dispute_resolved', 'new_message', 'rating_received',
'offer_matched', 'trade_reminder', 'system'
)),
title TEXT NOT NULL,
message TEXT,
-- Reference
reference_type VARCHAR(20) CHECK (reference_type IN ('trade', 'offer', 'dispute', 'message')),
reference_id UUID,
-- Status
is_read BOOLEAN DEFAULT FALSE,
read_at TIMESTAMPTZ,
-- Action URL (frontend route)
action_url TEXT,
-- Metadata
metadata JSONB DEFAULT '{}',
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes for p2p_notifications
CREATE INDEX idx_p2p_notifications_user ON public.p2p_notifications(user_id, created_at DESC);
CREATE INDEX idx_p2p_notifications_unread ON public.p2p_notifications(user_id, is_read) WHERE is_read = false;
CREATE INDEX idx_p2p_notifications_type ON public.p2p_notifications(user_id, type);
-- Enable RLS
ALTER TABLE public.p2p_notifications ENABLE ROW LEVEL SECURITY;
-- Policy: Users can only see their own notifications
CREATE POLICY "p2p_notifications_own" ON public.p2p_notifications
FOR ALL USING (user_id = auth.uid());
-- =====================================================
-- P2P DISPUTE EVIDENCE TABLE (Phase 3 - Dispute System)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_dispute_evidence (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
dispute_id UUID NOT NULL REFERENCES public.p2p_fiat_disputes(id) ON DELETE CASCADE,
uploaded_by UUID NOT NULL REFERENCES auth.users(id),
-- Evidence details
evidence_type VARCHAR(30) NOT NULL CHECK (evidence_type IN (
'screenshot', 'receipt', 'bank_statement', 'chat_log',
'transaction_proof', 'identity_doc', 'other'
)),
file_url TEXT NOT NULL,
file_name TEXT,
file_size INT, -- bytes
mime_type TEXT,
-- Description
description TEXT CHECK (LENGTH(description) <= 1000),
-- Admin review
reviewed_by UUID REFERENCES auth.users(id),
reviewed_at TIMESTAMPTZ,
review_notes TEXT,
is_valid BOOLEAN,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes for p2p_dispute_evidence
CREATE INDEX idx_p2p_evidence_dispute ON public.p2p_dispute_evidence(dispute_id, created_at);
CREATE INDEX idx_p2p_evidence_uploader ON public.p2p_dispute_evidence(uploaded_by);
-- Enable RLS
ALTER TABLE public.p2p_dispute_evidence ENABLE ROW LEVEL SECURITY;
-- Policy: Dispute parties can view evidence
CREATE POLICY "p2p_evidence_parties_read" ON public.p2p_dispute_evidence
FOR SELECT USING (
EXISTS (
SELECT 1 FROM public.p2p_fiat_disputes d
JOIN public.p2p_fiat_trades t ON t.id = d.trade_id
WHERE d.id = dispute_id
AND (t.seller_id = auth.uid() OR t.buyer_id = auth.uid() OR d.opened_by = auth.uid())
)
);
-- Policy: Dispute parties can upload evidence
CREATE POLICY "p2p_evidence_parties_insert" ON public.p2p_dispute_evidence
FOR INSERT WITH CHECK (
uploaded_by = auth.uid() AND
EXISTS (
SELECT 1 FROM public.p2p_fiat_disputes d
JOIN public.p2p_fiat_trades t ON t.id = d.trade_id
WHERE d.id = dispute_id
AND d.status IN ('open', 'under_review')
AND (t.seller_id = auth.uid() OR t.buyer_id = auth.uid())
)
);
-- Policy: Admins can view all evidence
CREATE POLICY "p2p_evidence_admin_read" ON public.p2p_dispute_evidence
FOR SELECT USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
-- Policy: Admins can update evidence (for review)
CREATE POLICY "p2p_evidence_admin_update" ON public.p2p_dispute_evidence
FOR UPDATE USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
-- =====================================================
-- P2P FRAUD REPORTS TABLE (Phase 3 - Security)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_fraud_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
reporter_id UUID NOT NULL REFERENCES auth.users(id),
reported_user_id UUID NOT NULL REFERENCES auth.users(id),
-- Report details
trade_id UUID REFERENCES public.p2p_fiat_trades(id),
reason VARCHAR(50) NOT NULL CHECK (reason IN (
'fake_payment', 'fake_proof', 'scam_attempt', 'harassment',
'money_laundering', 'identity_fraud', 'multiple_accounts', 'other'
)),
description TEXT NOT NULL CHECK (LENGTH(description) >= 20 AND LENGTH(description) <= 2000),
evidence_urls TEXT[] DEFAULT '{}',
-- Investigation
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN (
'pending', 'investigating', 'confirmed', 'dismissed', 'escalated'
)),
assigned_to UUID REFERENCES auth.users(id),
assigned_at TIMESTAMPTZ,
-- Resolution
resolution TEXT,
resolution_notes TEXT,
resolved_by UUID REFERENCES auth.users(id),
resolved_at TIMESTAMPTZ,
-- Action taken
action_taken VARCHAR(30) CHECK (action_taken IN (
'warning_issued', 'temporary_ban', 'permanent_ban',
'trade_restricted', 'no_action', 'referred_to_authorities'
)),
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
-- Constraints
CONSTRAINT cannot_report_self CHECK (reporter_id != reported_user_id)
);
-- Indexes for p2p_fraud_reports
CREATE INDEX idx_p2p_fraud_reporter ON public.p2p_fraud_reports(reporter_id);
CREATE INDEX idx_p2p_fraud_reported ON public.p2p_fraud_reports(reported_user_id);
CREATE INDEX idx_p2p_fraud_status ON public.p2p_fraud_reports(status) WHERE status IN ('pending', 'investigating');
CREATE INDEX idx_p2p_fraud_trade ON public.p2p_fraud_reports(trade_id) WHERE trade_id IS NOT NULL;
-- Enable RLS
ALTER TABLE public.p2p_fraud_reports ENABLE ROW LEVEL SECURITY;
-- Policy: Users can view their own reports
CREATE POLICY "p2p_fraud_own_reports" ON public.p2p_fraud_reports
FOR SELECT USING (reporter_id = auth.uid());
-- Policy: Users can create reports
CREATE POLICY "p2p_fraud_create" ON public.p2p_fraud_reports
FOR INSERT WITH CHECK (reporter_id = auth.uid());
-- Policy: Admins can view all reports
CREATE POLICY "p2p_fraud_admin_read" ON public.p2p_fraud_reports
FOR SELECT USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
-- Policy: Admins can update reports
CREATE POLICY "p2p_fraud_admin_update" ON public.p2p_fraud_reports
FOR UPDATE USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
-- =====================================================
-- TRIGGERS FOR UPDATED_AT
-- =====================================================
CREATE TRIGGER update_p2p_messages_updated_at BEFORE UPDATE ON public.p2p_messages
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_p2p_fraud_reports_updated_at BEFORE UPDATE ON public.p2p_fraud_reports
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-- =====================================================
-- ENABLE REALTIME FOR NEW TABLES
-- =====================================================
ALTER PUBLICATION supabase_realtime ADD TABLE public.p2p_messages;
ALTER PUBLICATION supabase_realtime ADD TABLE public.p2p_notifications;
-- =====================================================
-- NOTIFICATION TRIGGER FUNCTIONS
-- =====================================================
-- Function to create notification
CREATE OR REPLACE FUNCTION public.create_p2p_notification(
p_user_id UUID,
p_type TEXT,
p_title TEXT,
p_message TEXT DEFAULT NULL,
p_reference_type TEXT DEFAULT NULL,
p_reference_id UUID DEFAULT NULL,
p_action_url TEXT DEFAULT NULL,
p_metadata JSONB DEFAULT '{}'
) RETURNS UUID AS $$
DECLARE
v_notification_id UUID;
BEGIN
INSERT INTO public.p2p_notifications (
user_id, type, title, message,
reference_type, reference_id, action_url, metadata
) VALUES (
p_user_id, p_type, p_title, p_message,
p_reference_type, p_reference_id, p_action_url, p_metadata
)
RETURNING id INTO v_notification_id;
RETURN v_notification_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Trigger: Notify on new trade
CREATE OR REPLACE FUNCTION notify_on_new_trade()
RETURNS TRIGGER AS $$
DECLARE
v_offer RECORD;
BEGIN
-- Get offer details
SELECT * INTO v_offer FROM public.p2p_fiat_offers WHERE id = NEW.offer_id;
-- Notify seller about new order
PERFORM public.create_p2p_notification(
NEW.seller_id,
'new_order',
'New P2P Order',
format('Someone wants to buy %s %s', NEW.crypto_amount, v_offer.token),
'trade',
NEW.id,
format('/p2p/trade/%s', NEW.id)
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_notify_new_trade
AFTER INSERT ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION notify_on_new_trade();
-- Trigger: Notify on payment sent
CREATE OR REPLACE FUNCTION notify_on_payment_sent()
RETURNS TRIGGER AS $$
BEGIN
IF OLD.status = 'pending' AND NEW.status = 'payment_sent' THEN
PERFORM public.create_p2p_notification(
NEW.seller_id,
'payment_sent',
'Payment Marked as Sent',
'The buyer has marked the payment as sent. Please verify and release.',
'trade',
NEW.id,
format('/p2p/trade/%s', NEW.id)
);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_notify_payment_sent
AFTER UPDATE ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION notify_on_payment_sent();
-- Trigger: Notify on trade completed
CREATE OR REPLACE FUNCTION notify_on_trade_completed()
RETURNS TRIGGER AS $$
BEGIN
IF OLD.status != 'completed' AND NEW.status = 'completed' THEN
-- Notify buyer
PERFORM public.create_p2p_notification(
NEW.buyer_id,
'payment_confirmed',
'Trade Completed!',
'The seller has released the crypto. Check your wallet.',
'trade',
NEW.id,
format('/p2p/trade/%s', NEW.id)
);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_notify_trade_completed
AFTER UPDATE ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION notify_on_trade_completed();
-- Trigger: Notify on dispute opened
CREATE OR REPLACE FUNCTION notify_on_dispute_opened()
RETURNS TRIGGER AS $$
DECLARE
v_trade RECORD;
v_other_party UUID;
BEGIN
-- Get trade details
SELECT * INTO v_trade FROM public.p2p_fiat_trades WHERE id = NEW.trade_id;
-- Determine other party
IF NEW.opened_by = v_trade.seller_id THEN
v_other_party := v_trade.buyer_id;
ELSE
v_other_party := v_trade.seller_id;
END IF;
-- Notify the other party
PERFORM public.create_p2p_notification(
v_other_party,
'dispute_opened',
'Dispute Opened',
'A dispute has been opened for your trade. Please provide evidence.',
'dispute',
NEW.id,
format('/p2p/dispute/%s', NEW.id)
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_notify_dispute_opened
AFTER INSERT ON public.p2p_fiat_disputes
FOR EACH ROW EXECUTE FUNCTION notify_on_dispute_opened();
-- Trigger: Notify on new message
CREATE OR REPLACE FUNCTION notify_on_new_message()
RETURNS TRIGGER AS $$
DECLARE
v_trade RECORD;
v_recipient_id UUID;
BEGIN
-- Skip system messages
IF NEW.message_type = 'system' THEN
RETURN NEW;
END IF;
-- Get trade details
SELECT * INTO v_trade FROM public.p2p_fiat_trades WHERE id = NEW.trade_id;
-- Determine recipient
IF NEW.sender_id = v_trade.seller_id THEN
v_recipient_id := v_trade.buyer_id;
ELSE
v_recipient_id := v_trade.seller_id;
END IF;
-- Create notification
PERFORM public.create_p2p_notification(
v_recipient_id,
'new_message',
'New Message',
LEFT(NEW.message, 100),
'trade',
NEW.trade_id,
format('/p2p/trade/%s', NEW.trade_id)
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_notify_new_message
AFTER INSERT ON public.p2p_messages
FOR EACH ROW EXECUTE FUNCTION notify_on_new_message();
-- =====================================================
-- RATING HELPER FUNCTION
-- =====================================================
CREATE OR REPLACE FUNCTION public.update_user_rating_stats(p_user_id UUID)
RETURNS void AS $$
DECLARE
v_avg_rating NUMERIC;
v_total_ratings INT;
BEGIN
-- Calculate average rating
SELECT
AVG(rating)::NUMERIC(3,2),
COUNT(*)
INTO v_avg_rating, v_total_ratings
FROM public.p2p_ratings
WHERE rated_id = p_user_id;
-- Update reputation with rating info
UPDATE public.p2p_reputation
SET
updated_at = NOW()
-- Note: You could add avg_rating column to p2p_reputation if needed
WHERE user_id = p_user_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Trigger: Update stats after rating
CREATE OR REPLACE FUNCTION update_rating_stats_trigger()
RETURNS TRIGGER AS $$
BEGIN
PERFORM public.update_user_rating_stats(NEW.rated_id);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_update_rating_stats
AFTER INSERT ON public.p2p_ratings
FOR EACH ROW EXECUTE FUNCTION update_rating_stats_trigger();
-- =====================================================
-- GRANT EXECUTE PERMISSIONS
-- =====================================================
GRANT EXECUTE ON FUNCTION public.create_p2p_notification TO authenticated;
GRANT EXECUTE ON FUNCTION public.update_user_rating_stats TO authenticated;
-- =====================================================
-- ADD INDEXES FOR PERFORMANCE
-- =====================================================
-- Index for finding user's average rating quickly
CREATE INDEX idx_p2p_ratings_avg ON public.p2p_ratings(rated_id, rating);
-- Index for unread notification count
CREATE INDEX idx_p2p_notifications_unread_count ON public.p2p_notifications(user_id)
WHERE is_read = false;
-- =====================================================
-- COMMENTS FOR DOCUMENTATION
-- =====================================================
COMMENT ON TABLE public.p2p_messages IS 'Real-time chat messages between trade participants';
COMMENT ON TABLE public.p2p_ratings IS 'Post-trade ratings and reviews';
COMMENT ON TABLE public.p2p_notifications IS 'User notifications for P2P trading events';
COMMENT ON TABLE public.p2p_dispute_evidence IS 'Evidence files uploaded during disputes';
COMMENT ON TABLE public.p2p_fraud_reports IS 'Fraud reports submitted by users';
@@ -0,0 +1,456 @@
-- =====================================================
-- P2P FRAUD PREVENTION SYSTEM
-- Auto-detection rules and triggers
-- =====================================================
-- =====================================================
-- USER FRAUD INDICATORS TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_user_fraud_indicators (
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
-- Trade statistics
cancel_rate DECIMAL(5,2) DEFAULT 0, -- Percentage
dispute_rate DECIMAL(5,2) DEFAULT 0, -- Percentage
avg_trade_amount DECIMAL(18,2) DEFAULT 0,
-- Recent activity
recent_cancellations_24h INT DEFAULT 0,
recent_disputes_7d INT DEFAULT 0,
trades_today INT DEFAULT 0,
volume_today DECIMAL(18,2) DEFAULT 0,
-- Risk assessment
risk_score INT DEFAULT 0 CHECK (risk_score BETWEEN 0 AND 100),
risk_level VARCHAR(10) DEFAULT 'low' CHECK (risk_level IN ('low', 'medium', 'high', 'critical')),
active_flags TEXT[] DEFAULT '{}',
-- Restrictions
is_blocked BOOLEAN DEFAULT FALSE,
blocked_reason TEXT,
blocked_at TIMESTAMPTZ,
blocked_until TIMESTAMPTZ,
requires_review BOOLEAN DEFAULT FALSE,
-- Cooldowns
last_cancellation_at TIMESTAMPTZ,
last_dispute_at TIMESTAMPTZ,
last_trade_at TIMESTAMPTZ,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX idx_fraud_indicators_risk ON public.p2p_user_fraud_indicators(risk_score DESC);
CREATE INDEX idx_fraud_indicators_blocked ON public.p2p_user_fraud_indicators(is_blocked) WHERE is_blocked = true;
CREATE INDEX idx_fraud_indicators_review ON public.p2p_user_fraud_indicators(requires_review) WHERE requires_review = true;
-- Enable RLS
ALTER TABLE public.p2p_user_fraud_indicators ENABLE ROW LEVEL SECURITY;
-- Users can view their own indicators (limited)
CREATE POLICY "p2p_fraud_indicators_own_read" ON public.p2p_user_fraud_indicators
FOR SELECT USING (user_id = auth.uid());
-- Admins can view and update all
CREATE POLICY "p2p_fraud_indicators_admin" ON public.p2p_user_fraud_indicators
FOR ALL USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
-- =====================================================
-- SUSPICIOUS ACTIVITY LOG
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_suspicious_activity (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id),
trade_id UUID REFERENCES public.p2p_fiat_trades(id),
-- Activity details
activity_type VARCHAR(50) NOT NULL CHECK (activity_type IN (
'high_cancel_rate', 'frequent_disputes', 'rapid_trading',
'unusual_amount', 'new_account_large_trade', 'payment_name_mismatch',
'suspected_multi_account', 'ip_anomaly', 'device_anomaly', 'other'
)),
severity VARCHAR(10) NOT NULL CHECK (severity IN ('low', 'medium', 'high', 'critical')),
description TEXT,
metadata JSONB DEFAULT '{}',
-- Resolution
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'reviewed', 'dismissed', 'actioned')),
reviewed_by UUID REFERENCES auth.users(id),
reviewed_at TIMESTAMPTZ,
action_taken TEXT,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX idx_suspicious_activity_user ON public.p2p_suspicious_activity(user_id, created_at DESC);
CREATE INDEX idx_suspicious_activity_status ON public.p2p_suspicious_activity(status) WHERE status = 'pending';
CREATE INDEX idx_suspicious_activity_severity ON public.p2p_suspicious_activity(severity, created_at DESC);
-- Enable RLS
ALTER TABLE public.p2p_suspicious_activity ENABLE ROW LEVEL SECURITY;
-- Only admins can view
CREATE POLICY "p2p_suspicious_activity_admin" ON public.p2p_suspicious_activity
FOR ALL USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('moderator', 'admin')
)
);
-- =====================================================
-- FUNCTION: Calculate User Risk Score
-- =====================================================
CREATE OR REPLACE FUNCTION public.calculate_user_risk_score(p_user_id UUID)
RETURNS TABLE(
risk_score INT,
risk_level TEXT,
flags TEXT[]
) AS $$
DECLARE
v_indicators RECORD;
v_score INT := 0;
v_flags TEXT[] := '{}';
BEGIN
-- Get current indicators
SELECT * INTO v_indicators
FROM public.p2p_user_fraud_indicators
WHERE user_id = p_user_id;
-- If no record exists, create one
IF NOT FOUND THEN
INSERT INTO public.p2p_user_fraud_indicators (user_id)
VALUES (p_user_id)
RETURNING * INTO v_indicators;
END IF;
-- Calculate from reputation data
SELECT
COALESCE(
CASE WHEN total_trades > 0
THEN (cancelled_trades::DECIMAL / total_trades * 100)
ELSE 0
END, 0),
COALESCE(
CASE WHEN total_trades > 0
THEN (disputed_trades::DECIMAL / total_trades * 100)
ELSE 0
END, 0)
INTO v_indicators.cancel_rate, v_indicators.dispute_rate
FROM public.p2p_reputation
WHERE user_id = p_user_id;
-- Apply rules and calculate score
-- Rule 1: High cancel rate (>30%)
IF v_indicators.cancel_rate > 30 THEN
v_score := v_score + 25;
v_flags := array_append(v_flags, 'High Cancellation Rate');
END IF;
-- Rule 2: High dispute rate (>20%)
IF v_indicators.dispute_rate > 20 THEN
v_score := v_score + 30;
v_flags := array_append(v_flags, 'Frequent Disputes');
END IF;
-- Rule 3: Multiple recent cancellations (>3 in 24h)
IF v_indicators.recent_cancellations_24h > 3 THEN
v_score := v_score + 35;
v_flags := array_append(v_flags, 'Multiple Recent Cancellations');
END IF;
-- Rule 4: Recent disputes (>2 in 7d)
IF v_indicators.recent_disputes_7d > 2 THEN
v_score := v_score + 25;
v_flags := array_append(v_flags, 'Recent Disputes');
END IF;
-- Cap score at 100
v_score := LEAST(v_score, 100);
-- Determine risk level
risk_level := CASE
WHEN v_score >= 95 THEN 'critical'
WHEN v_score >= 80 THEN 'high'
WHEN v_score >= 50 THEN 'medium'
ELSE 'low'
END;
-- Update indicators table
UPDATE public.p2p_user_fraud_indicators
SET
risk_score = v_score,
risk_level = risk_level,
active_flags = v_flags,
is_blocked = (v_score >= 95),
requires_review = (v_score >= 80),
updated_at = NOW()
WHERE user_id = p_user_id;
risk_score := v_score;
flags := v_flags;
RETURN NEXT;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- FUNCTION: Check Trade Allowed
-- =====================================================
CREATE OR REPLACE FUNCTION public.check_trade_allowed(
p_user_id UUID,
p_trade_amount DECIMAL
) RETURNS TABLE(
allowed BOOLEAN,
reason TEXT
) AS $$
DECLARE
v_indicators RECORD;
v_reputation RECORD;
v_limits RECORD;
v_cooldown_ms BIGINT;
BEGIN
-- Get fraud indicators
SELECT * INTO v_indicators
FROM public.p2p_user_fraud_indicators
WHERE user_id = p_user_id;
-- Check if blocked
IF v_indicators IS NOT NULL AND v_indicators.is_blocked THEN
allowed := FALSE;
reason := COALESCE(v_indicators.blocked_reason, 'Your account is temporarily restricted from trading.');
RETURN NEXT;
RETURN;
END IF;
-- Check cooldown after cancellation (5 minutes)
IF v_indicators IS NOT NULL AND v_indicators.last_cancellation_at IS NOT NULL THEN
v_cooldown_ms := EXTRACT(EPOCH FROM (NOW() - v_indicators.last_cancellation_at)) * 1000;
IF v_cooldown_ms < 300000 THEN -- 5 minutes
allowed := FALSE;
reason := format('Please wait %s seconds before creating a new trade.', ((300000 - v_cooldown_ms) / 1000)::INT);
RETURN NEXT;
RETURN;
END IF;
END IF;
-- Check cooldown after dispute (24 hours)
IF v_indicators IS NOT NULL AND v_indicators.last_dispute_at IS NOT NULL THEN
v_cooldown_ms := EXTRACT(EPOCH FROM (NOW() - v_indicators.last_dispute_at)) * 1000;
IF v_cooldown_ms < 86400000 THEN -- 24 hours
allowed := FALSE;
reason := 'Trading is restricted for 24 hours after a dispute.';
RETURN NEXT;
RETURN;
END IF;
END IF;
-- Get reputation for trust level
SELECT * INTO v_reputation
FROM public.p2p_reputation
WHERE user_id = p_user_id;
-- Define limits based on trust level
SELECT * INTO v_limits FROM (
SELECT
CASE COALESCE(v_reputation.trust_level, 'new')
WHEN 'verified' THEN 50000
WHEN 'advanced' THEN 10000
WHEN 'intermediate' THEN 2000
WHEN 'basic' THEN 500
ELSE 100
END as max_trade,
CASE COALESCE(v_reputation.trust_level, 'new')
WHEN 'verified' THEN 50
WHEN 'advanced' THEN 20
WHEN 'intermediate' THEN 10
WHEN 'basic' THEN 5
ELSE 3
END as max_daily_trades,
CASE COALESCE(v_reputation.trust_level, 'new')
WHEN 'verified' THEN 100000
WHEN 'advanced' THEN 25000
WHEN 'intermediate' THEN 5000
WHEN 'basic' THEN 1000
ELSE 200
END as max_daily_volume
) limits;
-- Check trade amount limit
IF p_trade_amount > v_limits.max_trade THEN
allowed := FALSE;
reason := format('Trade amount exceeds your limit of $%s. Complete more trades to increase your limit.', v_limits.max_trade);
RETURN NEXT;
RETURN;
END IF;
-- Check daily trade count
IF v_indicators IS NOT NULL AND v_indicators.trades_today >= v_limits.max_daily_trades THEN
allowed := FALSE;
reason := format('You have reached your daily limit of %s trades.', v_limits.max_daily_trades);
RETURN NEXT;
RETURN;
END IF;
-- Check daily volume
IF v_indicators IS NOT NULL AND (v_indicators.volume_today + p_trade_amount) > v_limits.max_daily_volume THEN
allowed := FALSE;
reason := format('This trade would exceed your daily volume limit of $%s.', v_limits.max_daily_volume);
RETURN NEXT;
RETURN;
END IF;
-- All checks passed
allowed := TRUE;
reason := NULL;
RETURN NEXT;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- FUNCTION: Log Suspicious Activity
-- =====================================================
CREATE OR REPLACE FUNCTION public.log_suspicious_activity(
p_user_id UUID,
p_trade_id UUID,
p_activity_type TEXT,
p_severity TEXT,
p_description TEXT DEFAULT NULL,
p_metadata JSONB DEFAULT '{}'
) RETURNS UUID AS $$
DECLARE
v_activity_id UUID;
BEGIN
INSERT INTO public.p2p_suspicious_activity (
user_id, trade_id, activity_type, severity, description, metadata
) VALUES (
p_user_id, p_trade_id, p_activity_type, p_severity, p_description, p_metadata
)
RETURNING id INTO v_activity_id;
-- Auto-recalculate risk score
PERFORM public.calculate_user_risk_score(p_user_id);
RETURN v_activity_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- TRIGGER: Update Fraud Indicators on Trade Completion
-- =====================================================
CREATE OR REPLACE FUNCTION update_fraud_indicators_on_trade()
RETURNS TRIGGER AS $$
BEGIN
-- On trade completion
IF NEW.status = 'completed' AND (OLD.status IS NULL OR OLD.status != 'completed') THEN
-- Update buyer indicators
INSERT INTO public.p2p_user_fraud_indicators (user_id, trades_today, volume_today, last_trade_at)
VALUES (NEW.buyer_id, 1, NEW.fiat_amount, NOW())
ON CONFLICT (user_id) DO UPDATE SET
trades_today = p2p_user_fraud_indicators.trades_today + 1,
volume_today = p2p_user_fraud_indicators.volume_today + NEW.fiat_amount,
last_trade_at = NOW(),
updated_at = NOW();
-- Update seller indicators
INSERT INTO public.p2p_user_fraud_indicators (user_id, trades_today, volume_today, last_trade_at)
VALUES (NEW.seller_id, 1, NEW.fiat_amount, NOW())
ON CONFLICT (user_id) DO UPDATE SET
trades_today = p2p_user_fraud_indicators.trades_today + 1,
volume_today = p2p_user_fraud_indicators.volume_today + NEW.fiat_amount,
last_trade_at = NOW(),
updated_at = NOW();
END IF;
-- On trade cancellation
IF NEW.status = 'cancelled' AND (OLD.status IS NULL OR OLD.status != 'cancelled') THEN
IF NEW.cancelled_by IS NOT NULL THEN
UPDATE public.p2p_user_fraud_indicators
SET
recent_cancellations_24h = recent_cancellations_24h + 1,
last_cancellation_at = NOW(),
updated_at = NOW()
WHERE user_id = NEW.cancelled_by;
-- Recalculate risk score
PERFORM public.calculate_user_risk_score(NEW.cancelled_by);
END IF;
END IF;
-- On dispute
IF NEW.status = 'disputed' AND (OLD.status IS NULL OR OLD.status != 'disputed') THEN
-- Update both parties
UPDATE public.p2p_user_fraud_indicators
SET
recent_disputes_7d = recent_disputes_7d + 1,
last_dispute_at = NOW(),
updated_at = NOW()
WHERE user_id IN (NEW.buyer_id, NEW.seller_id);
-- Recalculate risk scores
PERFORM public.calculate_user_risk_score(NEW.buyer_id);
PERFORM public.calculate_user_risk_score(NEW.seller_id);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_update_fraud_indicators
AFTER UPDATE ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION update_fraud_indicators_on_trade();
-- =====================================================
-- SCHEDULED JOB: Reset Daily Counters
-- (Run at midnight UTC via pg_cron or external scheduler)
-- =====================================================
CREATE OR REPLACE FUNCTION public.reset_daily_fraud_counters()
RETURNS void AS $$
BEGIN
UPDATE public.p2p_user_fraud_indicators
SET
trades_today = 0,
volume_today = 0,
updated_at = NOW();
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- SCHEDULED JOB: Reset Weekly Counters
-- =====================================================
CREATE OR REPLACE FUNCTION public.reset_weekly_fraud_counters()
RETURNS void AS $$
BEGIN
UPDATE public.p2p_user_fraud_indicators
SET
recent_disputes_7d = 0,
updated_at = NOW();
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- GRANT PERMISSIONS
-- =====================================================
GRANT EXECUTE ON FUNCTION public.calculate_user_risk_score TO authenticated;
GRANT EXECUTE ON FUNCTION public.check_trade_allowed TO authenticated;
GRANT EXECUTE ON FUNCTION public.log_suspicious_activity TO authenticated;
GRANT EXECUTE ON FUNCTION public.reset_daily_fraud_counters TO authenticated;
GRANT EXECUTE ON FUNCTION public.reset_weekly_fraud_counters TO authenticated;
-- =====================================================
-- COMMENTS
-- =====================================================
COMMENT ON TABLE public.p2p_user_fraud_indicators IS 'Tracks fraud indicators and risk scores for P2P users';
COMMENT ON TABLE public.p2p_suspicious_activity IS 'Log of suspicious activities detected by the fraud system';
COMMENT ON FUNCTION public.calculate_user_risk_score IS 'Calculate and update user risk score based on trading behavior';
COMMENT ON FUNCTION public.check_trade_allowed IS 'Check if a user is allowed to make a trade based on limits and restrictions';
@@ -0,0 +1,534 @@
-- =====================================================
-- P2P MERCHANT SYSTEM - PHASE 4
-- Merchant tiers, stats, and advanced features
-- =====================================================
-- =====================================================
-- MERCHANT TIERS TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_merchant_tiers (
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
-- Tier info
tier VARCHAR(20) DEFAULT 'lite' CHECK (tier IN ('lite', 'super', 'diamond')),
-- Deposit (for higher tiers)
deposit_amount DECIMAL(18,2) DEFAULT 0,
deposit_token VARCHAR(10) DEFAULT 'HEZ',
deposit_tx_hash TEXT,
deposit_locked_at TIMESTAMPTZ,
-- Limits based on tier
max_pending_orders INT DEFAULT 5,
max_order_amount DECIMAL(18,2) DEFAULT 10000,
featured_ads_allowed INT DEFAULT 0,
-- Application status
application_status VARCHAR(20) CHECK (application_status IN ('pending', 'approved', 'rejected', 'suspended')),
applied_at TIMESTAMPTZ,
applied_for_tier VARCHAR(20),
approved_at TIMESTAMPTZ,
approved_by UUID REFERENCES auth.users(id),
rejection_reason TEXT,
-- Review
last_review_at TIMESTAMPTZ,
next_review_at TIMESTAMPTZ,
review_notes TEXT,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX idx_merchant_tiers_tier ON public.p2p_merchant_tiers(tier);
CREATE INDEX idx_merchant_tiers_pending ON public.p2p_merchant_tiers(application_status)
WHERE application_status = 'pending';
-- Enable RLS
ALTER TABLE public.p2p_merchant_tiers ENABLE ROW LEVEL SECURITY;
-- Users can view their own tier
CREATE POLICY "p2p_merchant_own_read" ON public.p2p_merchant_tiers
FOR SELECT USING (user_id = auth.uid());
-- Users can apply for tier (insert/update own)
CREATE POLICY "p2p_merchant_own_apply" ON public.p2p_merchant_tiers
FOR INSERT WITH CHECK (user_id = auth.uid());
CREATE POLICY "p2p_merchant_own_update" ON public.p2p_merchant_tiers
FOR UPDATE USING (user_id = auth.uid())
WITH CHECK (
-- Can only update application_status to 'pending' and applied_for_tier
user_id = auth.uid()
);
-- Public can see tier info (for display in ads)
CREATE POLICY "p2p_merchant_public_tier" ON public.p2p_merchant_tiers
FOR SELECT USING (true);
-- Admins can manage all
CREATE POLICY "p2p_merchant_admin" ON public.p2p_merchant_tiers
FOR ALL USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid() AND role IN ('admin')
)
);
-- =====================================================
-- MERCHANT STATS TABLE (Rolling 30-day stats)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_merchant_stats (
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
-- Volume stats (30 day rolling)
total_volume_30d DECIMAL(18,2) DEFAULT 0,
total_trades_30d INT DEFAULT 0,
buy_volume_30d DECIMAL(18,2) DEFAULT 0,
sell_volume_30d DECIMAL(18,2) DEFAULT 0,
-- Performance metrics
completion_rate_30d DECIMAL(5,2) DEFAULT 0,
avg_release_time_minutes INT,
avg_payment_time_minutes INT,
-- Lifetime stats
total_volume_lifetime DECIMAL(18,2) DEFAULT 0,
total_trades_lifetime INT DEFAULT 0,
-- Ranking
volume_rank INT,
trade_count_rank INT,
-- Timestamps
last_calculated_at TIMESTAMPTZ DEFAULT NOW(),
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX idx_merchant_stats_volume ON public.p2p_merchant_stats(total_volume_30d DESC);
CREATE INDEX idx_merchant_stats_trades ON public.p2p_merchant_stats(total_trades_30d DESC);
-- Enable RLS
ALTER TABLE public.p2p_merchant_stats ENABLE ROW LEVEL SECURITY;
-- Public read (for leaderboards)
CREATE POLICY "p2p_merchant_stats_public" ON public.p2p_merchant_stats
FOR SELECT USING (true);
-- =====================================================
-- FEATURED ADS TABLE
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_featured_ads (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
offer_id UUID NOT NULL REFERENCES public.p2p_fiat_offers(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES auth.users(id),
-- Featuring details
position INT DEFAULT 1, -- 1 = top, 2 = second, etc.
start_at TIMESTAMPTZ NOT NULL,
end_at TIMESTAMPTZ NOT NULL,
-- Payment
fee_amount DECIMAL(18,2) NOT NULL,
fee_token VARCHAR(10) DEFAULT 'HEZ',
fee_tx_hash TEXT,
paid_at TIMESTAMPTZ,
-- Status
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'active', 'expired', 'cancelled')),
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX idx_featured_ads_active ON public.p2p_featured_ads(status, start_at, end_at)
WHERE status = 'active';
CREATE INDEX idx_featured_ads_offer ON public.p2p_featured_ads(offer_id);
-- Enable RLS
ALTER TABLE public.p2p_featured_ads ENABLE ROW LEVEL SECURITY;
-- Users can view active featured ads
CREATE POLICY "p2p_featured_public_read" ON public.p2p_featured_ads
FOR SELECT USING (status = 'active' OR user_id = auth.uid());
-- Users can create featured ads for own offers
CREATE POLICY "p2p_featured_own_create" ON public.p2p_featured_ads
FOR INSERT WITH CHECK (
user_id = auth.uid() AND
EXISTS (
SELECT 1 FROM public.p2p_fiat_offers
WHERE id = offer_id AND seller_id = auth.uid()
)
);
-- =====================================================
-- USER PAYMENT METHODS (Saved methods)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_user_payment_methods (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
payment_method_id UUID NOT NULL REFERENCES public.payment_methods(id),
-- Account details (encrypted)
account_details_encrypted TEXT NOT NULL,
account_name TEXT, -- For display/verification
-- Settings
is_default BOOLEAN DEFAULT FALSE,
is_verified BOOLEAN DEFAULT FALSE,
verified_at TIMESTAMPTZ,
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes
CREATE INDEX idx_user_payment_methods_user ON public.p2p_user_payment_methods(user_id);
CREATE UNIQUE INDEX idx_user_payment_methods_default ON public.p2p_user_payment_methods(user_id)
WHERE is_default = true;
-- Enable RLS
ALTER TABLE public.p2p_user_payment_methods ENABLE ROW LEVEL SECURITY;
-- Users can manage own payment methods
CREATE POLICY "p2p_user_payment_own" ON public.p2p_user_payment_methods
FOR ALL USING (user_id = auth.uid());
-- =====================================================
-- TIER REQUIREMENTS CONSTANTS
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_tier_requirements (
tier VARCHAR(20) PRIMARY KEY,
min_trades INT NOT NULL,
min_completion_rate DECIMAL(5,2) NOT NULL,
min_volume_30d DECIMAL(18,2) NOT NULL,
deposit_required DECIMAL(18,2) NOT NULL,
deposit_token VARCHAR(10) DEFAULT 'HEZ',
max_pending_orders INT NOT NULL,
max_order_amount DECIMAL(18,2) NOT NULL,
featured_ads_allowed INT NOT NULL,
description TEXT
);
-- Insert tier requirements
INSERT INTO public.p2p_tier_requirements (tier, min_trades, min_completion_rate, min_volume_30d, deposit_required, max_pending_orders, max_order_amount, featured_ads_allowed, description)
VALUES
('lite', 0, 0, 0, 0, 5, 10000, 0, 'Basic tier for all verified users'),
('super', 20, 90, 5000, 10000, 20, 100000, 3, 'Professional trader tier with higher limits'),
('diamond', 100, 95, 25000, 50000, 50, 150000, 10, 'Elite merchant tier with maximum privileges')
ON CONFLICT (tier) DO UPDATE SET
min_trades = EXCLUDED.min_trades,
min_completion_rate = EXCLUDED.min_completion_rate,
min_volume_30d = EXCLUDED.min_volume_30d,
deposit_required = EXCLUDED.deposit_required,
max_pending_orders = EXCLUDED.max_pending_orders,
max_order_amount = EXCLUDED.max_order_amount,
featured_ads_allowed = EXCLUDED.featured_ads_allowed,
description = EXCLUDED.description;
-- =====================================================
-- FUNCTION: Check Tier Eligibility
-- =====================================================
CREATE OR REPLACE FUNCTION public.check_tier_eligibility(
p_user_id UUID,
p_target_tier VARCHAR(20)
) RETURNS TABLE(
eligible BOOLEAN,
missing_requirements TEXT[]
) AS $$
DECLARE
v_reputation RECORD;
v_stats RECORD;
v_requirements RECORD;
v_missing TEXT[] := '{}';
BEGIN
-- Get requirements
SELECT * INTO v_requirements
FROM public.p2p_tier_requirements
WHERE tier = p_target_tier;
IF NOT FOUND THEN
eligible := FALSE;
missing_requirements := ARRAY['Invalid tier'];
RETURN NEXT;
RETURN;
END IF;
-- Get user reputation
SELECT * INTO v_reputation
FROM public.p2p_reputation
WHERE user_id = p_user_id;
-- Get user stats
SELECT * INTO v_stats
FROM public.p2p_merchant_stats
WHERE user_id = p_user_id;
-- Check completed trades
IF COALESCE(v_reputation.completed_trades, 0) < v_requirements.min_trades THEN
v_missing := array_append(v_missing,
format('Need %s completed trades (have %s)',
v_requirements.min_trades,
COALESCE(v_reputation.completed_trades, 0)));
END IF;
-- Check completion rate
IF COALESCE(v_stats.completion_rate_30d, 0) < v_requirements.min_completion_rate THEN
v_missing := array_append(v_missing,
format('Need %s%% completion rate (have %s%%)',
v_requirements.min_completion_rate,
COALESCE(v_stats.completion_rate_30d, 0)));
END IF;
-- Check 30-day volume
IF COALESCE(v_stats.total_volume_30d, 0) < v_requirements.min_volume_30d THEN
v_missing := array_append(v_missing,
format('Need $%s 30-day volume (have $%s)',
v_requirements.min_volume_30d,
COALESCE(v_stats.total_volume_30d, 0)));
END IF;
-- Check deposit requirement
IF v_requirements.deposit_required > 0 THEN
v_missing := array_append(v_missing,
format('Deposit of %s %s required',
v_requirements.deposit_required,
v_requirements.deposit_token));
END IF;
eligible := array_length(v_missing, 1) IS NULL OR array_length(v_missing, 1) = 0;
missing_requirements := v_missing;
RETURN NEXT;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- FUNCTION: Apply for Tier Upgrade
-- =====================================================
CREATE OR REPLACE FUNCTION public.apply_for_tier_upgrade(
p_user_id UUID,
p_target_tier VARCHAR(20)
) RETURNS TABLE(
success BOOLEAN,
message TEXT
) AS $$
DECLARE
v_eligibility RECORD;
v_current_tier RECORD;
BEGIN
-- Check current tier
SELECT * INTO v_current_tier
FROM public.p2p_merchant_tiers
WHERE user_id = p_user_id;
-- Check if already at or above target tier
IF v_current_tier IS NOT NULL THEN
IF v_current_tier.tier = p_target_tier THEN
success := FALSE;
message := 'You are already at this tier';
RETURN NEXT;
RETURN;
END IF;
IF v_current_tier.application_status = 'pending' THEN
success := FALSE;
message := 'You already have a pending application';
RETURN NEXT;
RETURN;
END IF;
END IF;
-- Check eligibility
SELECT * INTO v_eligibility
FROM public.check_tier_eligibility(p_user_id, p_target_tier);
IF NOT v_eligibility.eligible THEN
success := FALSE;
message := 'Not eligible: ' || array_to_string(v_eligibility.missing_requirements, ', ');
RETURN NEXT;
RETURN;
END IF;
-- Create or update application
INSERT INTO public.p2p_merchant_tiers (
user_id, application_status, applied_at, applied_for_tier
) VALUES (
p_user_id, 'pending', NOW(), p_target_tier
)
ON CONFLICT (user_id) DO UPDATE SET
application_status = 'pending',
applied_at = NOW(),
applied_for_tier = p_target_tier,
updated_at = NOW();
success := TRUE;
message := 'Application submitted successfully';
RETURN NEXT;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- FUNCTION: Approve Tier Application (Admin)
-- =====================================================
CREATE OR REPLACE FUNCTION public.approve_tier_application(
p_user_id UUID,
p_admin_id UUID
) RETURNS void AS $$
DECLARE
v_application RECORD;
v_requirements RECORD;
BEGIN
-- Get application
SELECT * INTO v_application
FROM public.p2p_merchant_tiers
WHERE user_id = p_user_id AND application_status = 'pending';
IF NOT FOUND THEN
RAISE EXCEPTION 'No pending application found';
END IF;
-- Get tier requirements
SELECT * INTO v_requirements
FROM public.p2p_tier_requirements
WHERE tier = v_application.applied_for_tier;
-- Update tier
UPDATE public.p2p_merchant_tiers
SET
tier = v_application.applied_for_tier,
application_status = 'approved',
approved_at = NOW(),
approved_by = p_admin_id,
max_pending_orders = v_requirements.max_pending_orders,
max_order_amount = v_requirements.max_order_amount,
featured_ads_allowed = v_requirements.featured_ads_allowed,
updated_at = NOW()
WHERE user_id = p_user_id;
-- Create notification
PERFORM public.create_p2p_notification(
p_user_id,
'system',
'Tier Upgrade Approved!',
format('Congratulations! You have been upgraded to %s tier.', v_application.applied_for_tier),
NULL,
NULL,
'/p2p/merchant'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- FUNCTION: Calculate Merchant Stats
-- =====================================================
CREATE OR REPLACE FUNCTION public.calculate_merchant_stats(p_user_id UUID)
RETURNS void AS $$
DECLARE
v_stats RECORD;
BEGIN
-- Calculate 30-day stats
SELECT
COUNT(*) as trades_30d,
COALESCE(SUM(fiat_amount), 0) as volume_30d,
COALESCE(SUM(CASE WHEN buyer_id = p_user_id THEN fiat_amount ELSE 0 END), 0) as buy_volume,
COALESCE(SUM(CASE WHEN seller_id = p_user_id THEN fiat_amount ELSE 0 END), 0) as sell_volume,
COALESCE(
(COUNT(*) FILTER (WHERE status = 'completed')::DECIMAL /
NULLIF(COUNT(*), 0) * 100), 0
) as completion_rate,
AVG(EXTRACT(EPOCH FROM (seller_confirmed_at - buyer_marked_paid_at)) / 60)
FILTER (WHERE seller_id = p_user_id AND seller_confirmed_at IS NOT NULL) as avg_release,
AVG(EXTRACT(EPOCH FROM (buyer_marked_paid_at - created_at)) / 60)
FILTER (WHERE buyer_id = p_user_id AND buyer_marked_paid_at IS NOT NULL) as avg_payment
INTO v_stats
FROM public.p2p_fiat_trades
WHERE (buyer_id = p_user_id OR seller_id = p_user_id)
AND created_at >= NOW() - INTERVAL '30 days';
-- Upsert stats
INSERT INTO public.p2p_merchant_stats (
user_id,
total_volume_30d,
total_trades_30d,
buy_volume_30d,
sell_volume_30d,
completion_rate_30d,
avg_release_time_minutes,
avg_payment_time_minutes,
last_calculated_at
) VALUES (
p_user_id,
v_stats.volume_30d,
v_stats.trades_30d,
v_stats.buy_volume,
v_stats.sell_volume,
v_stats.completion_rate,
v_stats.avg_release::INT,
v_stats.avg_payment::INT,
NOW()
)
ON CONFLICT (user_id) DO UPDATE SET
total_volume_30d = v_stats.volume_30d,
total_trades_30d = v_stats.trades_30d,
buy_volume_30d = v_stats.buy_volume,
sell_volume_30d = v_stats.sell_volume,
completion_rate_30d = v_stats.completion_rate,
avg_release_time_minutes = v_stats.avg_release::INT,
avg_payment_time_minutes = v_stats.avg_payment::INT,
last_calculated_at = NOW();
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- =====================================================
-- TRIGGER: Update stats on trade completion
-- =====================================================
CREATE OR REPLACE FUNCTION update_merchant_stats_on_trade()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.status = 'completed' AND (OLD.status IS NULL OR OLD.status != 'completed') THEN
PERFORM public.calculate_merchant_stats(NEW.buyer_id);
PERFORM public.calculate_merchant_stats(NEW.seller_id);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER trigger_update_merchant_stats
AFTER UPDATE ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION update_merchant_stats_on_trade();
-- =====================================================
-- ADD is_featured COLUMN TO OFFERS
-- =====================================================
ALTER TABLE public.p2p_fiat_offers
ADD COLUMN IF NOT EXISTS is_featured BOOLEAN DEFAULT FALSE;
ALTER TABLE public.p2p_fiat_offers
ADD COLUMN IF NOT EXISTS featured_until TIMESTAMPTZ;
CREATE INDEX IF NOT EXISTS idx_p2p_offers_featured ON public.p2p_fiat_offers(is_featured, featured_until)
WHERE is_featured = true;
-- =====================================================
-- GRANTS
-- =====================================================
GRANT EXECUTE ON FUNCTION public.check_tier_eligibility TO authenticated;
GRANT EXECUTE ON FUNCTION public.apply_for_tier_upgrade TO authenticated;
GRANT EXECUTE ON FUNCTION public.approve_tier_application TO authenticated;
GRANT EXECUTE ON FUNCTION public.calculate_merchant_stats TO authenticated;
-- =====================================================
-- COMMENTS
-- =====================================================
COMMENT ON TABLE public.p2p_merchant_tiers IS 'Merchant tier assignments and applications';
COMMENT ON TABLE public.p2p_merchant_stats IS 'Rolling 30-day trading statistics for merchants';
COMMENT ON TABLE public.p2p_featured_ads IS 'Featured/promoted P2P advertisements';
COMMENT ON TABLE public.p2p_tier_requirements IS 'Requirements for each merchant tier level';
@@ -0,0 +1,14 @@
-- Add ad_type column to p2p_fiat_offers
-- This distinguishes between buy and sell offers
ALTER TABLE public.p2p_fiat_offers
ADD COLUMN IF NOT EXISTS ad_type TEXT NOT NULL DEFAULT 'sell'
CHECK (ad_type IN ('buy', 'sell'));
-- Add index for filtering by ad_type
CREATE INDEX IF NOT EXISTS idx_p2p_offers_ad_type ON public.p2p_fiat_offers(ad_type);
-- Update existing offers to be 'sell' type (default)
UPDATE public.p2p_fiat_offers SET ad_type = 'sell' WHERE ad_type IS NULL;
COMMENT ON COLUMN public.p2p_fiat_offers.ad_type IS 'Type of offer: buy (user wants to buy crypto) or sell (user wants to sell crypto)';
@@ -0,0 +1,11 @@
-- web/supabase/migrations/20260110120000_create_get_admins_function.sql
CREATE OR REPLACE FUNCTION public.get_admin_user_ids()
RETURNS TABLE(user_id UUID) AS $$
BEGIN
RETURN QUERY
SELECT ar.user_id
FROM public.admin_roles AS ar
WHERE ar.role IN ('admin', 'super_admin');
END;
$$ LANGUAGE plpgsql STABLE SECURITY DEFINER;
@@ -0,0 +1,46 @@
-- Migration: Drop auth.users FK constraints for wallet-based authentication
-- Since we moved from Supabase Auth to on-chain wallet verification,
-- user_id is now a deterministic UUID derived from wallet address (UUID v5)
-- and no longer corresponds to auth.users entries.
-- 1. Drop FK on p2p_deposit_withdraw_requests.user_id
ALTER TABLE public.p2p_deposit_withdraw_requests
DROP CONSTRAINT IF EXISTS p2p_deposit_withdraw_requests_user_id_fkey;
-- 2. Drop FK on p2p_deposit_withdraw_requests.processed_by
ALTER TABLE public.p2p_deposit_withdraw_requests
DROP CONSTRAINT IF EXISTS p2p_deposit_withdraw_requests_processed_by_fkey;
-- 3. Drop FK on user_internal_balances.user_id
ALTER TABLE public.user_internal_balances
DROP CONSTRAINT IF EXISTS user_internal_balances_user_id_fkey;
-- 4. Drop FK on p2p_balance_transactions.user_id (if table exists)
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_balance_transactions') THEN
ALTER TABLE public.p2p_balance_transactions DROP CONSTRAINT IF EXISTS p2p_balance_transactions_user_id_fkey;
END IF;
END $$;
-- 5. Drop FK on p2p_escrow_transactions (if table exists)
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_escrow_transactions') THEN
ALTER TABLE public.p2p_escrow_transactions DROP CONSTRAINT IF EXISTS p2p_escrow_transactions_buyer_id_fkey;
ALTER TABLE public.p2p_escrow_transactions DROP CONSTRAINT IF EXISTS p2p_escrow_transactions_seller_id_fkey;
END IF;
END $$;
-- 6. Drop FK on p2p_orders (if table exists)
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_orders') THEN
ALTER TABLE public.p2p_orders DROP CONSTRAINT IF EXISTS p2p_orders_user_id_fkey;
ALTER TABLE public.p2p_orders DROP CONSTRAINT IF EXISTS p2p_orders_merchant_id_fkey;
END IF;
END $$;
-- 7. Drop FK on p2p_ads (if table exists)
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_ads') THEN
ALTER TABLE public.p2p_ads DROP CONSTRAINT IF EXISTS p2p_ads_merchant_id_fkey;
END IF;
END $$;
@@ -0,0 +1,18 @@
-- Fix: Make blockchain_tx_hash unique constraint non-deferrable
-- PostgreSQL ON CONFLICT does not support deferrable constraints as arbiters
-- Drop the deferrable constraint (actual name from migration 016)
ALTER TABLE public.p2p_deposit_withdraw_requests
DROP CONSTRAINT IF EXISTS p2p_deposit_withdraw_requests_tx_hash_unique;
-- Also try the auto-generated name pattern
ALTER TABLE public.p2p_deposit_withdraw_requests
DROP CONSTRAINT IF EXISTS unique_blockchain_tx_hash;
-- Also try the default PostgreSQL naming convention
ALTER TABLE public.p2p_deposit_withdraw_requests
DROP CONSTRAINT IF EXISTS p2p_deposit_withdraw_requests_blockchain_tx_hash_key;
-- Recreate as non-deferrable (standard UNIQUE)
ALTER TABLE public.p2p_deposit_withdraw_requests
ADD CONSTRAINT p2p_deposit_withdraw_requests_tx_hash_unique UNIQUE (blockchain_tx_hash);
@@ -0,0 +1,85 @@
-- P2P Visa System
-- Provides identity for non-citizen P2P traders
-- Citizens use their on-chain Citizen Number (from NFT)
-- Non-citizens apply for a Visa (off-chain, stored in Supabase)
CREATE TABLE IF NOT EXISTS public.p2p_visa (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
visa_number TEXT UNIQUE NOT NULL,
wallet_address TEXT UNIQUE NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
trust_level INTEGER NOT NULL DEFAULT 1,
issued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ DEFAULT (now() + interval '1 year'),
metadata JSONB DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS idx_visa_wallet ON public.p2p_visa(wallet_address);
CREATE INDEX IF NOT EXISTS idx_visa_status ON public.p2p_visa(status);
-- Generate unique visa number: V-XXXXXX (6 digits)
CREATE OR REPLACE FUNCTION generate_visa_number()
RETURNS TEXT
LANGUAGE plpgsql
AS $$
DECLARE
num TEXT;
BEGIN
LOOP
num := 'V-' || lpad(floor(random() * 1000000)::text, 6, '0');
EXIT WHEN NOT EXISTS (SELECT 1 FROM public.p2p_visa WHERE visa_number = num);
END LOOP;
RETURN num;
END;
$$;
-- Issue a visa for a wallet address (returns the visa record)
CREATE OR REPLACE FUNCTION issue_p2p_visa(p_wallet_address TEXT)
RETURNS JSONB
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
v_visa_number TEXT;
v_result JSONB;
BEGIN
-- Check if wallet already has a visa
IF EXISTS (SELECT 1 FROM public.p2p_visa WHERE wallet_address = p_wallet_address AND status = 'active') THEN
SELECT jsonb_build_object(
'success', true,
'visa_number', visa_number,
'already_exists', true
) INTO v_result
FROM public.p2p_visa
WHERE wallet_address = p_wallet_address AND status = 'active';
RETURN v_result;
END IF;
-- Generate unique visa number
v_visa_number := generate_visa_number();
-- Insert new visa
INSERT INTO public.p2p_visa (visa_number, wallet_address)
VALUES (v_visa_number, p_wallet_address);
RETURN jsonb_build_object(
'success', true,
'visa_number', v_visa_number,
'already_exists', false
);
END;
$$;
-- RLS: service role only (P2P operations go through edge functions)
ALTER TABLE public.p2p_visa ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Service role full access on p2p_visa"
ON public.p2p_visa
FOR ALL
USING (auth.role() = 'service_role');
-- Allow anon/authenticated to read their own visa by wallet address
CREATE POLICY "Users can read own visa"
ON public.p2p_visa
FOR SELECT
USING (true);
@@ -0,0 +1,256 @@
-- Migration: Fix RLS policies for wallet-based authentication
--
-- Problem: All P2P RLS policies use auth.uid() which returns NULL because
-- users authenticate via wallet (not Supabase Auth). This blocks all access.
--
-- Solution: Replace auth.uid() policies with open access policies.
-- Security model:
-- - Financial mutations (escrow, deposits, withdrawals) go through SECURITY DEFINER RPCs
-- - Frontend queries filter by userId (UUID v5 derived from citizen/visa number)
-- - Edge functions use service_role key (bypass RLS)
-- - Admin operations check profiles.role in SECURITY DEFINER functions
-- ============================================================
-- 1. p2p_fiat_offers
-- ============================================================
DROP POLICY IF EXISTS "offers_seller_read_own" ON public.p2p_fiat_offers;
DROP POLICY IF EXISTS "offers_seller_insert" ON public.p2p_fiat_offers;
DROP POLICY IF EXISTS "offers_seller_update_own" ON public.p2p_fiat_offers;
DROP POLICY IF EXISTS "offers_seller_delete_own" ON public.p2p_fiat_offers;
-- Keep: offers_public_read_active (doesn't use auth.uid())
-- Sellers manage their own offers (anon key, no auth session)
CREATE POLICY "offers_anon_insert" ON public.p2p_fiat_offers
FOR INSERT WITH CHECK (true);
CREATE POLICY "offers_anon_update" ON public.p2p_fiat_offers
FOR UPDATE USING (true);
CREATE POLICY "offers_anon_delete" ON public.p2p_fiat_offers
FOR DELETE USING (true);
-- ============================================================
-- 2. p2p_fiat_trades
-- ============================================================
DROP POLICY IF EXISTS "trades_parties_read" ON public.p2p_fiat_trades;
DROP POLICY IF EXISTS "trades_buyer_insert" ON public.p2p_fiat_trades;
DROP POLICY IF EXISTS "trades_parties_update" ON public.p2p_fiat_trades;
CREATE POLICY "trades_anon_select" ON public.p2p_fiat_trades
FOR SELECT USING (true);
CREATE POLICY "trades_anon_insert" ON public.p2p_fiat_trades
FOR INSERT WITH CHECK (true);
CREATE POLICY "trades_anon_update" ON public.p2p_fiat_trades
FOR UPDATE USING (true);
-- ============================================================
-- 3. p2p_fiat_disputes
-- ============================================================
DROP POLICY IF EXISTS "disputes_parties_read" ON public.p2p_fiat_disputes;
DROP POLICY IF EXISTS "disputes_moderators_read" ON public.p2p_fiat_disputes;
DROP POLICY IF EXISTS "disputes_parties_insert" ON public.p2p_fiat_disputes;
CREATE POLICY "disputes_anon_select" ON public.p2p_fiat_disputes
FOR SELECT USING (true);
CREATE POLICY "disputes_anon_insert" ON public.p2p_fiat_disputes
FOR INSERT WITH CHECK (true);
CREATE POLICY "disputes_anon_update" ON public.p2p_fiat_disputes
FOR UPDATE USING (true);
-- ============================================================
-- 4. p2p_dispute_evidence
-- ============================================================
-- May not have RLS enabled yet, ensure it does with open policies
ALTER TABLE IF EXISTS public.p2p_dispute_evidence ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "evidence_anon_select" ON public.p2p_dispute_evidence;
DROP POLICY IF EXISTS "evidence_anon_insert" ON public.p2p_dispute_evidence;
CREATE POLICY "evidence_anon_select" ON public.p2p_dispute_evidence
FOR SELECT USING (true);
CREATE POLICY "evidence_anon_insert" ON public.p2p_dispute_evidence
FOR INSERT WITH CHECK (true);
-- ============================================================
-- 5. p2p_messages (chat)
-- ============================================================
ALTER TABLE IF EXISTS public.p2p_messages ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "messages_anon_select" ON public.p2p_messages;
DROP POLICY IF EXISTS "messages_anon_insert" ON public.p2p_messages;
DROP POLICY IF EXISTS "messages_anon_update" ON public.p2p_messages;
CREATE POLICY "messages_anon_select" ON public.p2p_messages
FOR SELECT USING (true);
CREATE POLICY "messages_anon_insert" ON public.p2p_messages
FOR INSERT WITH CHECK (true);
CREATE POLICY "messages_anon_update" ON public.p2p_messages
FOR UPDATE USING (true);
-- ============================================================
-- 6. p2p_notifications
-- ============================================================
ALTER TABLE IF EXISTS public.p2p_notifications ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "notifications_anon_select" ON public.p2p_notifications;
DROP POLICY IF EXISTS "notifications_anon_insert" ON public.p2p_notifications;
DROP POLICY IF EXISTS "notifications_anon_update" ON public.p2p_notifications;
CREATE POLICY "notifications_anon_select" ON public.p2p_notifications
FOR SELECT USING (true);
CREATE POLICY "notifications_anon_insert" ON public.p2p_notifications
FOR INSERT WITH CHECK (true);
CREATE POLICY "notifications_anon_update" ON public.p2p_notifications
FOR UPDATE USING (true);
-- ============================================================
-- 7. p2p_ratings
-- ============================================================
ALTER TABLE IF EXISTS public.p2p_ratings ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "ratings_anon_select" ON public.p2p_ratings;
DROP POLICY IF EXISTS "ratings_anon_insert" ON public.p2p_ratings;
CREATE POLICY "ratings_anon_select" ON public.p2p_ratings
FOR SELECT USING (true);
CREATE POLICY "ratings_anon_insert" ON public.p2p_ratings
FOR INSERT WITH CHECK (true);
-- ============================================================
-- 8. p2p_block_trade_requests
-- ============================================================
ALTER TABLE IF EXISTS public.p2p_block_trade_requests ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "block_trades_anon_select" ON public.p2p_block_trade_requests;
DROP POLICY IF EXISTS "block_trades_anon_insert" ON public.p2p_block_trade_requests;
CREATE POLICY "block_trades_anon_select" ON public.p2p_block_trade_requests
FOR SELECT USING (true);
CREATE POLICY "block_trades_anon_insert" ON public.p2p_block_trade_requests
FOR INSERT WITH CHECK (true);
-- ============================================================
-- 9. p2p_merchant_tiers
-- ============================================================
ALTER TABLE IF EXISTS public.p2p_merchant_tiers ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "merchant_tiers_anon_select" ON public.p2p_merchant_tiers;
CREATE POLICY "merchant_tiers_anon_select" ON public.p2p_merchant_tiers
FOR SELECT USING (true);
-- ============================================================
-- 10. p2p_merchant_stats
-- ============================================================
ALTER TABLE IF EXISTS public.p2p_merchant_stats ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "merchant_stats_anon_select" ON public.p2p_merchant_stats;
CREATE POLICY "merchant_stats_anon_select" ON public.p2p_merchant_stats
FOR SELECT USING (true);
-- ============================================================
-- 11. p2p_reputation (already has open SELECT, keep it)
-- ============================================================
-- reputation_public_read already uses USING (true) - no change needed
-- ============================================================
-- 12. user_internal_balances
-- Reads go through RPC get_user_internal_balance (SECURITY DEFINER)
-- But drop the auth.uid() policies to prevent errors
-- ============================================================
DROP POLICY IF EXISTS "Users can view own balances" ON public.user_internal_balances;
DROP POLICY IF EXISTS "Admins can view all balances" ON public.user_internal_balances;
CREATE POLICY "balances_anon_select" ON public.user_internal_balances
FOR SELECT USING (true);
-- ============================================================
-- 13. p2p_deposit_withdraw_requests
-- Reads from frontend, writes via SECURITY DEFINER RPCs + edge functions
-- ============================================================
DROP POLICY IF EXISTS "Users can view own requests" ON public.p2p_deposit_withdraw_requests;
DROP POLICY IF EXISTS "Users can create own requests" ON public.p2p_deposit_withdraw_requests;
DROP POLICY IF EXISTS "Admins can manage all requests" ON public.p2p_deposit_withdraw_requests;
CREATE POLICY "deposit_requests_anon_select" ON public.p2p_deposit_withdraw_requests
FOR SELECT USING (true);
-- Writes handled by service_role (edge functions) and SECURITY DEFINER RPCs
CREATE POLICY "deposit_requests_service_write" ON public.p2p_deposit_withdraw_requests
FOR ALL USING (auth.role() = 'service_role');
-- ============================================================
-- 14. p2p_balance_transactions
-- Read-only from frontend
-- ============================================================
DROP POLICY IF EXISTS "Users can view own transactions" ON public.p2p_balance_transactions;
CREATE POLICY "balance_tx_anon_select" ON public.p2p_balance_transactions
FOR SELECT USING (true);
-- ============================================================
-- 15. p2p_audit_log - keep restricted
-- ============================================================
DROP POLICY IF EXISTS "audit_user_read_own" ON public.p2p_audit_log;
DROP POLICY IF EXISTS "audit_admin_read_all" ON public.p2p_audit_log;
DROP POLICY IF EXISTS "p2p_audit_log_admin_only" ON public.p2p_audit_log;
-- Audit log: open INSERT (shared lib writes via anon key), SELECT for service_role
CREATE POLICY "audit_log_anon_insert" ON public.p2p_audit_log
FOR INSERT WITH CHECK (true);
CREATE POLICY "audit_log_service_select" ON public.p2p_audit_log
FOR SELECT USING (auth.role() = 'service_role');
-- ============================================================
-- 16. p2p_platform_escrow - keep restricted to service_role (if exists)
-- ============================================================
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_platform_escrow') THEN
EXECUTE 'DROP POLICY IF EXISTS "Sellers can view their escrow" ON public.p2p_platform_escrow';
EXECUTE 'DROP POLICY IF EXISTS "Admins can view all escrow" ON public.p2p_platform_escrow';
EXECUTE 'CREATE POLICY "escrow_service_only" ON public.p2p_platform_escrow FOR ALL USING (auth.role() = ''service_role'')';
END IF;
END $$;
-- ============================================================
-- 17. platform_escrow_balance - keep restricted (if exists)
-- ============================================================
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'platform_escrow_balance') THEN
EXECUTE 'DROP POLICY IF EXISTS "escrow_admin_only" ON public.platform_escrow_balance';
EXECUTE 'CREATE POLICY "escrow_balance_service_only" ON public.platform_escrow_balance FOR ALL USING (auth.role() = ''service_role'')';
END IF;
END $$;
-- ============================================================
-- 18. p2p_user_payment_methods (if exists)
-- ============================================================
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_user_payment_methods') THEN
ALTER TABLE public.p2p_user_payment_methods ENABLE ROW LEVEL SECURITY;
EXECUTE 'DROP POLICY IF EXISTS "user_pm_anon_select" ON public.p2p_user_payment_methods';
EXECUTE 'DROP POLICY IF EXISTS "user_pm_anon_insert" ON public.p2p_user_payment_methods';
EXECUTE 'DROP POLICY IF EXISTS "user_pm_anon_update" ON public.p2p_user_payment_methods';
EXECUTE 'CREATE POLICY "user_pm_anon_select" ON public.p2p_user_payment_methods FOR SELECT USING (true)';
EXECUTE 'CREATE POLICY "user_pm_anon_insert" ON public.p2p_user_payment_methods FOR INSERT WITH CHECK (true)';
EXECUTE 'CREATE POLICY "user_pm_anon_update" ON public.p2p_user_payment_methods FOR UPDATE USING (true)';
END IF;
END $$;
-- ============================================================
-- Done. All P2P tables now work with wallet-based auth.
-- Financial security maintained through SECURITY DEFINER RPCs.
-- ============================================================
@@ -0,0 +1,276 @@
-- =====================================================
-- P2P ATOMIC ESCROW & PLATFORM WALLET SYSTEM
-- Migration: 013_p2p_atomic_escrow.sql
-- =====================================================
-- 1. Platform escrow wallet tracking table
CREATE TABLE IF NOT EXISTS p2p_platform_escrow (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
offer_id UUID NOT NULL REFERENCES p2p_fiat_offers(id) ON DELETE CASCADE,
seller_id UUID NOT NULL REFERENCES auth.users(id),
seller_wallet TEXT NOT NULL,
token TEXT NOT NULL,
amount DECIMAL(20, 12) NOT NULL,
locked_at TIMESTAMPTZ DEFAULT NOW(),
released_at TIMESTAMPTZ,
released_to TEXT, -- wallet address
release_reason TEXT, -- 'trade_complete', 'trade_cancelled', 'trade_expired', 'refund'
blockchain_tx_lock TEXT, -- tx hash for lock transfer
blockchain_tx_release TEXT, -- tx hash for release transfer
status TEXT NOT NULL DEFAULT 'locked' CHECK (status IN ('locked', 'released', 'pending_release')),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Index for quick lookups
CREATE INDEX IF NOT EXISTS idx_platform_escrow_offer ON p2p_platform_escrow(offer_id);
CREATE INDEX IF NOT EXISTS idx_platform_escrow_seller ON p2p_platform_escrow(seller_id);
CREATE INDEX IF NOT EXISTS idx_platform_escrow_status ON p2p_platform_escrow(status);
-- 2. Atomic function to accept offer (prevents race condition)
CREATE OR REPLACE FUNCTION accept_p2p_offer(
p_offer_id UUID,
p_buyer_id UUID,
p_buyer_wallet TEXT,
p_amount DECIMAL(20, 12)
) RETURNS JSON AS $$
DECLARE
v_offer RECORD;
v_trade_id UUID;
v_payment_deadline TIMESTAMPTZ;
v_fiat_amount DECIMAL(20, 2);
BEGIN
-- Lock the offer row for update (prevents concurrent modifications)
SELECT * INTO v_offer
FROM p2p_fiat_offers
WHERE id = p_offer_id
FOR UPDATE;
-- Validation checks
IF v_offer IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Offer not found');
END IF;
IF v_offer.status != 'open' THEN
RETURN json_build_object('success', false, 'error', 'Offer is not available');
END IF;
IF v_offer.seller_id = p_buyer_id THEN
RETURN json_build_object('success', false, 'error', 'Cannot buy from your own offer');
END IF;
IF p_amount > v_offer.remaining_amount THEN
RETURN json_build_object('success', false, 'error', 'Insufficient remaining amount. Available: ' || v_offer.remaining_amount);
END IF;
IF v_offer.min_order_amount IS NOT NULL AND p_amount < v_offer.min_order_amount THEN
RETURN json_build_object('success', false, 'error', 'Minimum order: ' || v_offer.min_order_amount || ' ' || v_offer.token);
END IF;
IF v_offer.max_order_amount IS NOT NULL AND p_amount > v_offer.max_order_amount THEN
RETURN json_build_object('success', false, 'error', 'Maximum order: ' || v_offer.max_order_amount || ' ' || v_offer.token);
END IF;
-- Calculate fiat amount
v_fiat_amount := (p_amount / v_offer.amount_crypto) * v_offer.fiat_amount;
v_payment_deadline := NOW() + (v_offer.time_limit_minutes || ' minutes')::INTERVAL;
-- Create trade
INSERT INTO p2p_fiat_trades (
offer_id,
seller_id,
buyer_id,
buyer_wallet,
crypto_amount,
fiat_amount,
price_per_unit,
escrow_locked_amount,
escrow_locked_at,
status,
payment_deadline
) VALUES (
p_offer_id,
v_offer.seller_id,
p_buyer_id,
p_buyer_wallet,
p_amount,
v_fiat_amount,
v_offer.price_per_unit,
p_amount,
NOW(),
'pending',
v_payment_deadline
) RETURNING id INTO v_trade_id;
-- Atomically update remaining amount
UPDATE p2p_fiat_offers
SET
remaining_amount = remaining_amount - p_amount,
status = CASE
WHEN remaining_amount - p_amount = 0 THEN 'locked'
ELSE 'open'
END,
updated_at = NOW()
WHERE id = p_offer_id;
RETURN json_build_object(
'success', true,
'trade_id', v_trade_id,
'crypto_amount', p_amount,
'fiat_amount', v_fiat_amount,
'payment_deadline', v_payment_deadline
);
END;
$$ LANGUAGE plpgsql;
-- 3. Function to release escrow on trade completion
CREATE OR REPLACE FUNCTION complete_p2p_trade(
p_trade_id UUID,
p_seller_id UUID
) RETURNS JSON AS $$
DECLARE
v_trade RECORD;
BEGIN
-- Lock trade row
SELECT * INTO v_trade
FROM p2p_fiat_trades
WHERE id = p_trade_id
FOR UPDATE;
IF v_trade IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Trade not found');
END IF;
IF v_trade.seller_id != p_seller_id THEN
RETURN json_build_object('success', false, 'error', 'Only seller can confirm receipt');
END IF;
IF v_trade.status != 'payment_sent' THEN
RETURN json_build_object('success', false, 'error', 'Payment not marked as sent yet');
END IF;
-- Update trade status
UPDATE p2p_fiat_trades
SET
status = 'completed',
completed_at = NOW(),
updated_at = NOW()
WHERE id = p_trade_id;
-- Update escrow status (will be released by backend)
UPDATE p2p_platform_escrow
SET
status = 'pending_release',
released_to = v_trade.buyer_wallet,
release_reason = 'trade_complete',
updated_at = NOW()
WHERE offer_id = v_trade.offer_id
AND status = 'locked';
RETURN json_build_object(
'success', true,
'buyer_wallet', v_trade.buyer_wallet,
'amount', v_trade.crypto_amount,
'token', (SELECT token FROM p2p_fiat_offers WHERE id = v_trade.offer_id)
);
END;
$$ LANGUAGE plpgsql;
-- 4. Function to cancel/expire trade (return to seller)
CREATE OR REPLACE FUNCTION cancel_p2p_trade(
p_trade_id UUID,
p_user_id UUID,
p_reason TEXT DEFAULT 'cancelled'
) RETURNS JSON AS $$
DECLARE
v_trade RECORD;
v_offer RECORD;
BEGIN
-- Lock trade row
SELECT * INTO v_trade
FROM p2p_fiat_trades
WHERE id = p_trade_id
FOR UPDATE;
IF v_trade IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Trade not found');
END IF;
-- Only buyer can cancel before payment, or system for expiry
IF v_trade.status = 'pending' AND v_trade.buyer_id != p_user_id THEN
RETURN json_build_object('success', false, 'error', 'Only buyer can cancel pending trade');
END IF;
IF v_trade.status NOT IN ('pending', 'payment_sent') THEN
RETURN json_build_object('success', false, 'error', 'Trade cannot be cancelled in current status');
END IF;
-- Get offer details
SELECT * INTO v_offer FROM p2p_fiat_offers WHERE id = v_trade.offer_id;
-- Update trade status
UPDATE p2p_fiat_trades
SET
status = 'cancelled',
cancelled_at = NOW(),
cancelled_by = p_user_id,
updated_at = NOW()
WHERE id = p_trade_id;
-- Return amount to offer
UPDATE p2p_fiat_offers
SET
remaining_amount = remaining_amount + v_trade.crypto_amount,
status = 'open',
updated_at = NOW()
WHERE id = v_trade.offer_id;
RETURN json_build_object(
'success', true,
'refunded_amount', v_trade.crypto_amount,
'reason', p_reason
);
END;
$$ LANGUAGE plpgsql;
-- 5. RLS policies for platform escrow
ALTER TABLE p2p_platform_escrow ENABLE ROW LEVEL SECURITY;
-- Sellers can view their own escrow
CREATE POLICY "Sellers can view their escrow"
ON p2p_platform_escrow FOR SELECT
USING (seller_id = auth.uid());
-- Admins can view all escrow
CREATE POLICY "Admins can view all escrow"
ON p2p_platform_escrow FOR SELECT
USING (
EXISTS (
SELECT 1 FROM profiles
WHERE profiles.id = auth.uid()
AND profiles.role IN ('admin', 'super_admin')
)
);
-- Only system can insert/update (via service role)
-- No INSERT/UPDATE policies for regular users
-- 6. Add platform_wallet_address to config
CREATE TABLE IF NOT EXISTS p2p_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
description TEXT,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Insert platform wallet config (will be updated with real address)
INSERT INTO p2p_config (key, value, description)
VALUES (
'platform_escrow_wallet',
'5DFwqK698vL4gXHEcanaewnAqhxJ2rjhAogpSTHw3iwGDwd3',
'Platform wallet address for P2P escrow'
)
ON CONFLICT (key) DO NOTHING;
COMMENT ON TABLE p2p_platform_escrow IS 'Tracks all escrow deposits for P2P trades';
COMMENT ON TABLE p2p_config IS 'P2P system configuration';
@@ -0,0 +1,31 @@
-- Migration: Drop remaining auth.users FK constraints missed in 20260223120000
-- These tables still reference auth.users(id) but use wallet-based UUID v5 identity
-- 1. p2p_messages.sender_id (blocks chat)
ALTER TABLE public.p2p_messages
DROP CONSTRAINT IF EXISTS p2p_messages_sender_id_fkey;
-- 2. p2p_notifications.user_id (blocks notifications)
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_notifications') THEN
ALTER TABLE public.p2p_notifications DROP CONSTRAINT IF EXISTS p2p_notifications_user_id_fkey;
END IF;
END $$;
-- 3. p2p_ratings.rater_id, rated_id
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_ratings') THEN
ALTER TABLE public.p2p_ratings DROP CONSTRAINT IF EXISTS p2p_ratings_rater_id_fkey;
ALTER TABLE public.p2p_ratings DROP CONSTRAINT IF EXISTS p2p_ratings_rated_id_fkey;
END IF;
END $$;
-- 4. p2p_audit_log.user_id
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'p2p_audit_log') THEN
ALTER TABLE public.p2p_audit_log DROP CONSTRAINT IF EXISTS p2p_audit_log_user_id_fkey;
END IF;
END $$;
-- 5. Drop old auth.uid() RLS policy on p2p_messages (replaced by open policy)
DROP POLICY IF EXISTS "p2p_messages_trade_participants" ON public.p2p_messages;
@@ -0,0 +1,62 @@
-- Payment proof lifecycle: auto-delete after 1 day, retain if disputed
-- 1. Add proof_expires_at column
ALTER TABLE public.p2p_fiat_trades
ADD COLUMN IF NOT EXISTS proof_expires_at TIMESTAMPTZ;
-- 2. Function to clean up expired payment proofs
-- Called by pg_cron or Edge Function daily
CREATE OR REPLACE FUNCTION cleanup_expired_payment_proofs()
RETURNS JSON AS $$
DECLARE
v_count INT := 0;
v_trade RECORD;
BEGIN
FOR v_trade IN
SELECT id, buyer_payment_proof_url
FROM p2p_fiat_trades
WHERE buyer_payment_proof_url IS NOT NULL
AND proof_expires_at IS NOT NULL
AND proof_expires_at < NOW()
AND status NOT IN ('disputed')
LOOP
UPDATE p2p_fiat_trades
SET buyer_payment_proof_url = NULL,
proof_expires_at = NULL,
updated_at = NOW()
WHERE id = v_trade.id;
v_count := v_count + 1;
END LOOP;
RETURN json_build_object('success', true, 'cleaned', v_count);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- 3. Function to retain proof when dispute is opened (set expires_at = NULL)
CREATE OR REPLACE FUNCTION retain_payment_proof(p_trade_id UUID)
RETURNS JSON AS $$
BEGIN
UPDATE p2p_fiat_trades
SET proof_expires_at = NULL,
updated_at = NOW()
WHERE id = p_trade_id
AND buyer_payment_proof_url IS NOT NULL;
RETURN json_build_object('success', true);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- 4. Moderator function to delete proof after dispute resolution
CREATE OR REPLACE FUNCTION moderator_clear_payment_proof(p_trade_id UUID)
RETURNS JSON AS $$
BEGIN
UPDATE p2p_fiat_trades
SET buyer_payment_proof_url = NULL,
proof_expires_at = NULL,
updated_at = NOW()
WHERE id = p_trade_id;
RETURN json_build_object('success', true);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
@@ -0,0 +1,18 @@
-- Storage policies for p2p-payment-proofs bucket
-- Users are wallet-based (no auth.uid()), so policies must be open
-- Proof files auto-expire in 1 day via cleanup-proofs edge function
-- Allow anyone to upload payment proofs
CREATE POLICY "Allow payment proof uploads"
ON storage.objects FOR INSERT
WITH CHECK (bucket_id = 'p2p-payment-proofs');
-- Allow anyone to read payment proofs (public bucket)
CREATE POLICY "Allow payment proof reads"
ON storage.objects FOR SELECT
USING (bucket_id = 'p2p-payment-proofs');
-- Allow deletion (for cleanup-proofs edge function via service role)
CREATE POLICY "Allow payment proof deletes"
ON storage.objects FOR DELETE
USING (bucket_id = 'p2p-payment-proofs');
@@ -0,0 +1,13 @@
-- Migration: Drop auth.users FK constraint on p2p_withdrawal_limits
-- This table was missed in 20260223120000 and 20260224050000 migrations.
-- user_id is now a deterministic UUID v5 derived from citizen/visa number,
-- not an auth.users entry. The FK causes check_withdrawal_limit() to fail
-- with a constraint violation on INSERT.
ALTER TABLE public.p2p_withdrawal_limits
DROP CONSTRAINT IF EXISTS p2p_withdrawal_limits_user_id_fkey;
-- Also drop the ON DELETE CASCADE since auth.users is no longer the source
-- The constraint name may vary; try the default naming convention too
ALTER TABLE public.p2p_withdrawal_limits
DROP CONSTRAINT IF EXISTS p2p_withdrawal_limits_pkey_fkey;
@@ -0,0 +1,10 @@
ALTER TABLE admin_roles ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Admins can view admin roles" ON admin_roles;
DROP POLICY IF EXISTS "Super admins can manage admin roles" ON admin_roles;
DROP POLICY IF EXISTS "authenticated_read_admin_roles" ON admin_roles;
CREATE POLICY "authenticated_read_admin_roles"
ON admin_roles FOR SELECT
TO authenticated
USING (true);
@@ -0,0 +1,118 @@
-- =====================================================
-- Migration: Withdrawal authorization hardening
-- Date: 2026-07-25
-- =====================================================
--
-- Part of the fix for the CRITICAL broken-object-level-auth finding on the
-- withdrawal path. Two defenses:
--
-- 1. Replay protection for the signed withdrawal challenge (nonce store).
-- 2. Defense-in-depth: request_withdraw() may ONLY be executed by the backend
-- service role. Previously it was executable by anon/authenticated, so an
-- attacker with the public anon key could call it directly with a victim's
-- user_id to create a pending withdrawal to an attacker-controlled wallet,
-- which the batch processor would then pay out.
--
-- =====================================================
-- 1. CHALLENGE NONCE STORE (single-use signed challenges)
-- =====================================================
CREATE TABLE IF NOT EXISTS public.p2p_challenge_nonces (
nonce TEXT PRIMARY KEY,
purpose TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_p2p_challenge_nonces_created
ON public.p2p_challenge_nonces(created_at);
ALTER TABLE public.p2p_challenge_nonces ENABLE ROW LEVEL SECURITY;
-- Only the service role (edge functions) may read/write nonces.
DROP POLICY IF EXISTS "challenge_nonces_service_only" ON public.p2p_challenge_nonces;
CREATE POLICY "challenge_nonces_service_only" ON public.p2p_challenge_nonces
FOR ALL USING (auth.role() = 'service_role') WITH CHECK (auth.role() = 'service_role');
REVOKE ALL ON public.p2p_challenge_nonces FROM anon, authenticated, PUBLIC;
-- =====================================================
-- 2. LOCK request_withdraw() TO SERVICE ROLE
-- =====================================================
-- Recreate with an explicit service-role guard (mirrors process_deposit()).
CREATE OR REPLACE FUNCTION request_withdraw(
p_user_id UUID,
p_token TEXT,
p_amount DECIMAL(20, 12),
p_wallet_address TEXT
) RETURNS JSON AS $$
DECLARE
v_balance RECORD;
v_request_id UUID;
BEGIN
-- SECURITY: backend service role only. Object-level authorization (proving the
-- caller owns p_user_id) is enforced by the process-withdraw edge function via
-- a verified wallet signature before this is ever invoked.
IF current_setting('role', true) <> 'service_role'
AND current_setting('request.jwt.claim.role', true) <> 'service_role' THEN
RETURN json_build_object(
'success', false,
'error', 'UNAUTHORIZED: withdrawals must go through the backend service'
);
END IF;
-- Lock user's balance
SELECT * INTO v_balance
FROM user_internal_balances
WHERE user_id = p_user_id AND token = p_token
FOR UPDATE;
-- Check sufficient available balance
IF v_balance IS NULL OR v_balance.available_balance < p_amount THEN
RETURN json_build_object(
'success', false,
'error', 'Insufficient available balance. Available: ' || COALESCE(v_balance.available_balance, 0)
);
END IF;
-- Lock the amount (move to locked_balance)
UPDATE user_internal_balances
SET
available_balance = available_balance - p_amount,
locked_balance = locked_balance + p_amount,
updated_at = NOW()
WHERE user_id = p_user_id AND token = p_token;
-- Create withdrawal request
INSERT INTO p2p_deposit_withdraw_requests (
user_id, request_type, token, amount, wallet_address, status
) VALUES (
p_user_id, 'withdraw', p_token, p_amount, p_wallet_address, 'pending'
) RETURNING id INTO v_request_id;
-- Log the transaction
INSERT INTO p2p_balance_transactions (
user_id, token, transaction_type, amount,
balance_before, balance_after, reference_type, reference_id,
description
) VALUES (
p_user_id, p_token, 'withdraw', -p_amount,
v_balance.available_balance, v_balance.available_balance - p_amount, 'withdraw_request', v_request_id,
'Withdrawal request to ' || p_wallet_address
);
RETURN json_build_object(
'success', true,
'request_id', v_request_id,
'amount', p_amount,
'wallet_address', p_wallet_address,
'status', 'pending'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
REVOKE EXECUTE ON FUNCTION request_withdraw(UUID, TEXT, DECIMAL, TEXT) FROM PUBLIC, anon, authenticated;
COMMENT ON FUNCTION request_withdraw IS
'Create withdrawal request and lock balance. SERVICE ROLE ONLY — called by the
process-withdraw edge function after it verifies the caller owns the identity via
a wallet signature. Never call directly from the client.';
@@ -0,0 +1,122 @@
-- =====================================================
-- Migration: Harden RLS on financial + PII tables
-- Date: 2026-07-25
-- =====================================================
--
-- Forward migration (does NOT rewrite history) that removes the blanket
-- `USING (true)` read policies added in 20260223160000_fix_rls_for_wallet_auth
-- on the crown-jewel financial/PII tables, so the public anon key can no longer
-- enumerate every user's balances, ledger history, deposit/withdraw requests, or
-- payment-method PII.
--
-- Reads the app legitimately needs are moved behind SECURITY DEFINER RPCs that
-- return only the requested user's rows (instead of the whole table). Writes to
-- these tables already go through service_role edge functions / SECURITY DEFINER
-- RPCs, so no client write path is affected.
--
-- NOTE (residual, tracked): user_id is a UUID v5 derived from a citizen/visa
-- number, which is not a secret. These RPCs remove full-table exfiltration but do
-- not yet cryptographically bind the reader to the row owner. Fully closing that
-- requires a signed-session read path (same mechanism as withdrawals) applied to
-- these reads — see the security report. The high-severity leak (dump ALL rows)
-- is closed here.
-- =====================================================
-- 1. user_internal_balances — no direct client reads (uses
-- get_user_internal_balance RPC which is SECURITY DEFINER and bypasses RLS)
-- =====================================================
DROP POLICY IF EXISTS "balances_anon_select" ON public.user_internal_balances;
-- No anon policy remains -> anon/authenticated cannot read the table directly.
-- SECURITY DEFINER RPCs (get_user_internal_balance) continue to work.
-- =====================================================
-- 2. p2p_balance_transactions — replace open SELECT with a scoped RPC
-- =====================================================
DROP POLICY IF EXISTS "balance_tx_anon_select" ON public.p2p_balance_transactions;
CREATE OR REPLACE FUNCTION public.get_user_balance_transactions(
p_user_id UUID,
p_limit INT DEFAULT 50
) RETURNS SETOF public.p2p_balance_transactions AS $$
SELECT *
FROM public.p2p_balance_transactions
WHERE user_id = p_user_id
ORDER BY created_at DESC
LIMIT LEAST(GREATEST(COALESCE(p_limit, 50), 1), 200);
$$ LANGUAGE sql STABLE SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION public.get_user_balance_transactions(UUID, INT) TO anon, authenticated;
COMMENT ON FUNCTION public.get_user_balance_transactions IS
'Returns balance-transaction history for a single user_id only (no full-table
dump). Replaces the removed USING(true) SELECT policy.';
-- =====================================================
-- 3. p2p_deposit_withdraw_requests — replace open SELECT with a scoped RPC
-- (service_role write policy from 20260223160000 is retained)
-- =====================================================
DROP POLICY IF EXISTS "deposit_requests_anon_select" ON public.p2p_deposit_withdraw_requests;
CREATE OR REPLACE FUNCTION public.get_user_deposit_withdraw_requests(
p_user_id UUID,
p_limit INT DEFAULT 50
) RETURNS SETOF public.p2p_deposit_withdraw_requests AS $$
SELECT *
FROM public.p2p_deposit_withdraw_requests
WHERE user_id = p_user_id
ORDER BY created_at DESC
LIMIT LEAST(GREATEST(COALESCE(p_limit, 50), 1), 200);
$$ LANGUAGE sql STABLE SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION public.get_user_deposit_withdraw_requests(UUID, INT) TO anon, authenticated;
COMMENT ON FUNCTION public.get_user_deposit_withdraw_requests IS
'Returns deposit/withdraw requests for a single user_id only. Replaces the
removed USING(true) SELECT policy.';
-- =====================================================
-- 4. p2p_user_payment_methods (IBAN / payment PII) — lock to service role
-- (no direct client access exists; offers embed encrypted payment details).
-- =====================================================
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'p2p_user_payment_methods') THEN
EXECUTE 'ALTER TABLE public.p2p_user_payment_methods ENABLE ROW LEVEL SECURITY';
EXECUTE 'DROP POLICY IF EXISTS "user_pm_anon_select" ON public.p2p_user_payment_methods';
EXECUTE 'DROP POLICY IF EXISTS "user_pm_anon_insert" ON public.p2p_user_payment_methods';
EXECUTE 'DROP POLICY IF EXISTS "user_pm_anon_update" ON public.p2p_user_payment_methods';
EXECUTE 'DROP POLICY IF EXISTS "user_pm_service_only" ON public.p2p_user_payment_methods';
EXECUTE 'CREATE POLICY "user_pm_service_only" ON public.p2p_user_payment_methods
FOR ALL USING (auth.role() = ''service_role'') WITH CHECK (auth.role() = ''service_role'')';
EXECUTE 'REVOKE ALL ON public.p2p_user_payment_methods FROM anon, authenticated, PUBLIC';
END IF;
END $$;
-- =====================================================
-- 5. p2p_fiat_disputes — remove world-open UPDATE.
-- Dispute state transitions (claim/resolve) now go through the service-role
-- `resolve-dispute` edge function (which verifies the admin wallet signature).
-- Regular users still INSERT disputes (disputes_anon_insert retained).
-- =====================================================
DROP POLICY IF EXISTS "disputes_anon_update" ON public.p2p_fiat_disputes;
DROP POLICY IF EXISTS "disputes_service_update" ON public.p2p_fiat_disputes;
CREATE POLICY "disputes_service_update" ON public.p2p_fiat_disputes
FOR UPDATE USING (auth.role() = 'service_role') WITH CHECK (auth.role() = 'service_role');
-- =====================================================
-- Done. Balances, ledger, deposit/withdraw requests and payment PII are no longer
-- world-readable via the anon key; dispute resolution is no longer world-writable.
--
-- RESIDUAL (documented in the security report, NOT closed here to avoid breaking
-- the live app without the signed-session refactor):
-- * p2p_fiat_offers / p2p_fiat_trades / p2p_messages still carry USING(true)
-- policies because the client reads/writes them directly with the anon key
-- and there is no server session to bind to. Marking a trade status does not
-- itself move funds.
-- * The internal-ledger escrow RPCs (lock_/release_/refund_escrow_internal)
-- are still EXECUTE-able by anon (confirmPaymentReceived / createFiatOffer
-- call them directly). This is a SEPARATE critical hole that needs the same
-- signed-challenge mechanism applied to trade actions (an authenticated
-- confirm-payment / create-offer edge function). See report.
-- =====================================================
@@ -0,0 +1,158 @@
-- =====================================================
-- Migration: Atomic admin dispute resolution (moves escrow)
-- Date: 2026-07-25
-- =====================================================
--
-- Fix for the CRITICAL fund-logic finding: the admin Dispute Resolution panel
-- only relabelled p2p_fiat_trades.status and NEVER moved escrow, so "buyer wins"
-- paid nothing, "refund seller" left funds locked, and "split" was unhandled.
--
-- This SECURITY DEFINER function performs the escrow movement AND all status
-- changes in a single transaction. It is service-role only; caller identity
-- (admin) is verified by the resolve-dispute edge function via a wallet
-- signature before this is invoked.
--
-- ESCROW ACCOUNTING (verified against createFiatOffer + accept_p2p_offer):
-- * createFiatOffer locks the FULL offer amount (available -> locked).
-- * accept_p2p_offer does NOT lock again; it only decrements
-- offer.remaining_amount. So: seller.locked == remaining_amount + SUM(active
-- trade amounts) for the offer.
-- Therefore, per trade of amount X:
-- - release_to_buyer : locked(seller) -= X, available(buyer) += X. (offer untouched)
-- - refund_to_seller : locked(seller) -= X, available(seller) += X. (offer untouched)
-- - split : release X/2 to buyer + refund X/2 to seller. (offer untouched)
-- remaining_amount is intentionally NOT restored (that would double-count the
-- funds — a latent bug in the older resolve_p2p_dispute()).
CREATE OR REPLACE FUNCTION public.admin_resolve_dispute(
p_dispute_id UUID,
p_trade_id UUID,
p_decision TEXT, -- 'release_to_buyer' | 'refund_to_seller' | 'split' | 'escalate'
p_reasoning TEXT,
p_admin_ref TEXT -- admin wallet address (for audit only)
) RETURNS JSON AS $$
DECLARE
v_trade RECORD;
v_token TEXT;
v_half DECIMAL(20, 12);
v_res JSON;
v_trade_status TEXT;
BEGIN
-- SECURITY: backend service role only. Admin identity is verified upstream by
-- the resolve-dispute edge function (wallet signature vs. admin wallet set).
IF current_setting('role', true) <> 'service_role'
AND current_setting('request.jwt.claim.role', true) <> 'service_role' THEN
RETURN json_build_object('success', false, 'error', 'UNAUTHORIZED: service role required');
END IF;
IF p_reasoning IS NULL OR length(trim(p_reasoning)) = 0 THEN
RETURN json_build_object('success', false, 'error', 'Reasoning is required');
END IF;
IF p_decision NOT IN ('release_to_buyer', 'refund_to_seller', 'split', 'escalate') THEN
RETURN json_build_object('success', false, 'error', 'Invalid decision');
END IF;
-- Lock the trade row
SELECT * INTO v_trade FROM public.p2p_fiat_trades WHERE id = p_trade_id FOR UPDATE;
IF NOT FOUND THEN
RETURN json_build_object('success', false, 'error', 'Trade not found');
END IF;
-- ----- ESCALATE: no fund movement, just mark dispute escalated -----
IF p_decision = 'escalate' THEN
UPDATE public.p2p_fiat_disputes
SET status = 'escalated', decision = 'escalate', decision_reasoning = p_reasoning, updated_at = NOW()
WHERE id = p_dispute_id;
INSERT INTO public.p2p_audit_log (user_id, action, entity_type, entity_id, details)
VALUES (NULL, 'dispute_escalated', 'trade', p_trade_id,
jsonb_build_object('dispute_id', p_dispute_id, 'admin_ref', p_admin_ref, 'reasoning', p_reasoning));
RETURN json_build_object('success', true, 'decision', 'escalate');
END IF;
-- For fund-moving decisions the trade must be in dispute.
IF v_trade.status <> 'disputed' THEN
RETURN json_build_object('success', false, 'error', 'Trade is not in disputed status (current: ' || v_trade.status || ')');
END IF;
-- Resolve token from the offer
SELECT token INTO v_token FROM public.p2p_fiat_offers WHERE id = v_trade.offer_id;
IF v_token IS NULL THEN
RETURN json_build_object('success', false, 'error', 'Offer/token not found for trade');
END IF;
IF p_decision = 'release_to_buyer' THEN
v_res := public.release_escrow_internal(
v_trade.seller_id, v_trade.buyer_id, v_token, v_trade.crypto_amount, 'dispute_resolution', p_trade_id);
IF (v_res->>'success')::boolean IS NOT TRUE THEN
RAISE EXCEPTION 'release_escrow_internal failed: %', COALESCE(v_res->>'error', 'unknown');
END IF;
v_trade_status := 'completed';
ELSIF p_decision = 'refund_to_seller' THEN
v_res := public.refund_escrow_internal(
v_trade.seller_id, v_token, v_trade.crypto_amount, 'dispute_resolution', p_trade_id);
IF (v_res->>'success')::boolean IS NOT TRUE THEN
RAISE EXCEPTION 'refund_escrow_internal failed: %', COALESCE(v_res->>'error', 'unknown');
END IF;
v_trade_status := 'refunded';
ELSIF p_decision = 'split' THEN
v_half := ROUND(v_trade.crypto_amount / 2, 12);
-- Half to buyer
v_res := public.release_escrow_internal(
v_trade.seller_id, v_trade.buyer_id, v_token, v_half, 'dispute_resolution_split', p_trade_id);
IF (v_res->>'success')::boolean IS NOT TRUE THEN
RAISE EXCEPTION 'split release failed: %', COALESCE(v_res->>'error', 'unknown');
END IF;
-- Remainder back to seller (handles odd cents deterministically)
v_res := public.refund_escrow_internal(
v_trade.seller_id, v_token, v_trade.crypto_amount - v_half, 'dispute_resolution_split', p_trade_id);
IF (v_res->>'success')::boolean IS NOT TRUE THEN
RAISE EXCEPTION 'split refund failed: %', COALESCE(v_res->>'error', 'unknown');
END IF;
v_trade_status := 'completed';
END IF;
-- Update trade
UPDATE public.p2p_fiat_trades
SET status = v_trade_status,
completed_at = CASE WHEN v_trade_status = 'completed' THEN NOW() ELSE completed_at END,
escrow_released_at = NOW(),
dispute_resolved_at = NOW(),
dispute_resolution = p_decision || ': ' || COALESCE(p_reasoning, ''),
updated_at = NOW()
WHERE id = p_trade_id;
-- Update dispute
UPDATE public.p2p_fiat_disputes
SET status = 'resolved', decision = p_decision, decision_reasoning = p_reasoning,
resolved_at = NOW(), updated_at = NOW()
WHERE id = p_dispute_id;
-- Notify both parties (best-effort, same txn)
INSERT INTO public.p2p_notifications (user_id, type, title, message, reference_type, reference_id)
VALUES
(v_trade.seller_id, 'dispute_resolved', 'Dispute Resolved', 'Your dispute was resolved: ' || p_decision, 'dispute', p_dispute_id),
(v_trade.buyer_id, 'dispute_resolved', 'Dispute Resolved', 'Your dispute was resolved: ' || p_decision, 'dispute', p_dispute_id);
-- Audit
INSERT INTO public.p2p_audit_log (user_id, action, entity_type, entity_id, details)
VALUES (NULL, 'dispute_resolved', 'trade', p_trade_id,
jsonb_build_object(
'dispute_id', p_dispute_id, 'decision', p_decision, 'admin_ref', p_admin_ref,
'reasoning', p_reasoning, 'seller_id', v_trade.seller_id, 'buyer_id', v_trade.buyer_id,
'amount', v_trade.crypto_amount, 'token', v_token));
RETURN json_build_object('success', true, 'decision', p_decision, 'trade_id', p_trade_id, 'token', v_token, 'amount', v_trade.crypto_amount);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
REVOKE EXECUTE ON FUNCTION public.admin_resolve_dispute(UUID, UUID, TEXT, TEXT, TEXT) FROM PUBLIC, anon, authenticated;
COMMENT ON FUNCTION public.admin_resolve_dispute IS
'Atomically resolves a P2P dispute: moves escrow (release/refund/split) AND
updates trade + dispute status + notifications in one transaction. SERVICE ROLE
ONLY — admin identity is verified by the resolve-dispute edge function.';
@@ -0,0 +1,52 @@
-- =====================================================
-- Migration: Lock down internal-ledger escrow RPCs
-- Date: 2026-07-25
-- =====================================================
--
-- Fix for the CRITICAL drain: lock_/release_/refund_escrow_internal (migration
-- 014) had default PUBLIC EXECUTE, and the client called release_escrow_internal
-- directly with the public anon key. An anon caller could therefore run
-- release_escrow_internal(victim, attacker, token, amount)
-- and drain any victim's LOCKED balance.
--
-- These functions now execute ONLY as the service role. Every legitimate caller
-- goes through a service-role edge function that first verifies a wallet
-- signature + identity ownership:
-- * release -> confirm-payment edge function (seller-authorized)
-- * lock -> lock-escrow edge function (owner-authorized)
-- * refund -> process-withdraw (on failed payout) + admin_resolve_dispute
-- (dispute refunds/splits). No direct client caller.
--
-- SECURITY DEFINER functions that call these internally (admin_resolve_dispute,
-- cancel_expired_trades, process_deposit) are unaffected: EXECUTE for an inner
-- call is checked against the function OWNER, not the session role.
-- release_escrow_internal(p_from_user_id, p_to_user_id, p_token, p_amount, p_reference_type, p_reference_id)
REVOKE EXECUTE ON FUNCTION release_escrow_internal(UUID, UUID, TEXT, DECIMAL, TEXT, UUID)
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION release_escrow_internal(UUID, UUID, TEXT, DECIMAL, TEXT, UUID)
TO service_role;
-- refund_escrow_internal(p_user_id, p_token, p_amount, p_reference_type, p_reference_id)
REVOKE EXECUTE ON FUNCTION refund_escrow_internal(UUID, TEXT, DECIMAL, TEXT, UUID)
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION refund_escrow_internal(UUID, TEXT, DECIMAL, TEXT, UUID)
TO service_role;
-- lock_escrow_internal(p_user_id, p_token, p_amount, p_reference_type, p_reference_id)
REVOKE EXECUTE ON FUNCTION lock_escrow_internal(UUID, TEXT, DECIMAL, TEXT, UUID)
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION lock_escrow_internal(UUID, TEXT, DECIMAL, TEXT, UUID)
TO service_role;
COMMENT ON FUNCTION release_escrow_internal IS
'Release escrow seller->buyer. SERVICE ROLE ONLY — invoked by the confirm-payment
edge function after verifying the seller''s wallet signature + identity ownership.';
COMMENT ON FUNCTION refund_escrow_internal IS
'Refund locked escrow to its owner. SERVICE ROLE ONLY — invoked by process-withdraw
(failed payout) and admin_resolve_dispute (dispute refund/split).';
COMMENT ON FUNCTION lock_escrow_internal IS
'Lock a user''s own available balance into escrow. SERVICE ROLE ONLY — invoked by
the lock-escrow edge function after verifying the caller owns that identity.';
@@ -0,0 +1,109 @@
-- =====================================================
-- Migration: Freeze fund-routing columns on trades/offers
-- Date: 2026-07-25
-- =====================================================
--
-- Fix for a CONFIRMED custody-critical escrow-redirection bypass.
--
-- p2p_fiat_trades still carries a world-open UPDATE policy
-- (trades_anon_update USING(true), migration 20260223160000) because the client
-- legitimately flips status / uploads payment proof with the anon key, and there
-- is no server session to bind row ownership to. The 20260725010000 hardening
-- migration knowingly left this, on the assumption that "marking a trade status
-- does not itself move funds".
--
-- That assumption is INCOMPLETE. The seller-authorized release path
-- (confirm-payment edge function) and admin_resolve_dispute() read the fund
-- DESTINATION and AMOUNT from the trade row at release time:
-- release_escrow_internal(trade.seller_id, trade.buyer_id, token, trade.crypto_amount)
-- Because buyer_id / crypto_amount / offer_id are attacker-writable via the anon
-- key, an external attacker can do
-- UPDATE p2p_fiat_trades SET buyer_id = <attacker> WHERE id = <victim_trade>
-- and, when the honest seller signs the (correctly authenticated) release, the
-- escrow is paid to the attacker instead of the buyer who sent fiat. The
-- signature gate is intact but authorizes a row whose routing was tampered.
--
-- Minimal fix (no app-breaking change, no signed-session refactor required):
-- make the fund-routing / amount columns IMMUTABLE after insert via a BEFORE
-- UPDATE trigger. No legitimate code path ever mutates these columns after the
-- trade/offer is created (accept_p2p_offer INSERTs them; every UPDATE — status,
-- proof, timestamps, dispute fields, remaining_amount, price edits — leaves them
-- untouched). The service role is still allowed to change them so future
-- backend tooling / manual reconciliation is not boxed in.
-- -----------------------------------------------------
-- 1. p2p_fiat_trades: freeze routing + amount columns
-- -----------------------------------------------------
CREATE OR REPLACE FUNCTION public.enforce_trade_financial_immutability()
RETURNS TRIGGER AS $$
BEGIN
-- Allow the backend service role to change anything (reconciliation).
IF current_setting('role', true) = 'service_role'
OR current_setting('request.jwt.claim.role', true) = 'service_role' THEN
RETURN NEW;
END IF;
IF NEW.offer_id IS DISTINCT FROM OLD.offer_id
OR NEW.seller_id IS DISTINCT FROM OLD.seller_id
OR NEW.buyer_id IS DISTINCT FROM OLD.buyer_id
OR NEW.crypto_amount IS DISTINCT FROM OLD.crypto_amount
OR NEW.fiat_amount IS DISTINCT FROM OLD.fiat_amount
OR NEW.price_per_unit IS DISTINCT FROM OLD.price_per_unit
OR NEW.escrow_locked_amount IS DISTINCT FROM OLD.escrow_locked_amount THEN
RAISE EXCEPTION 'Trade fund-routing columns are immutable (offer_id, seller_id, buyer_id, crypto_amount, fiat_amount, price_per_unit, escrow_locked_amount)';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_freeze_trade_financials ON public.p2p_fiat_trades;
CREATE TRIGGER trg_freeze_trade_financials
BEFORE UPDATE ON public.p2p_fiat_trades
FOR EACH ROW EXECUTE FUNCTION public.enforce_trade_financial_immutability();
-- -----------------------------------------------------
-- 2. p2p_fiat_offers: freeze token / seller / original amount
-- (token drives WHICH balance release_escrow_internal moves; seller_id is the
-- escrow owner). Status, remaining_amount, price and fiat fields stay editable
-- so the existing offer edit / pause / partial-fill flows keep working.
-- -----------------------------------------------------
CREATE OR REPLACE FUNCTION public.enforce_offer_financial_immutability()
RETURNS TRIGGER AS $$
BEGIN
IF current_setting('role', true) = 'service_role'
OR current_setting('request.jwt.claim.role', true) = 'service_role' THEN
RETURN NEW;
END IF;
IF NEW.seller_id IS DISTINCT FROM OLD.seller_id
OR NEW.token IS DISTINCT FROM OLD.token
OR NEW.amount_crypto IS DISTINCT FROM OLD.amount_crypto THEN
RAISE EXCEPTION 'Offer fund-routing columns are immutable (seller_id, token, amount_crypto)';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_freeze_offer_financials ON public.p2p_fiat_offers;
CREATE TRIGGER trg_freeze_offer_financials
BEFORE UPDATE ON public.p2p_fiat_offers
FOR EACH ROW EXECUTE FUNCTION public.enforce_offer_financial_immutability();
COMMENT ON FUNCTION public.enforce_trade_financial_immutability IS
'Blocks anon/authenticated UPDATEs from changing a trade''s fund-routing/amount
columns (escrow redirection defense). Service role is exempt.';
COMMENT ON FUNCTION public.enforce_offer_financial_immutability IS
'Blocks anon/authenticated UPDATEs from changing an offer''s seller/token/amount
(escrow token mis-routing defense). Service role is exempt.';
-- ---------------------------------------------------------------------------
-- 3. Remove the dead legacy escrow-mover from the anon attack surface.
-- resolve_p2p_dispute() is SECURITY DEFINER and moves escrow, but its
-- auth.uid() admin gate is NULL under the public anon key, so it already
-- fails closed for anon. Revoking PUBLIC/anon/authenticated EXECUTE removes
-- it as an attack surface entirely (dispute resolution now flows through the
-- wallet-signed resolve-dispute edge function + admin_resolve_dispute).
-- ---------------------------------------------------------------------------
REVOKE EXECUTE ON FUNCTION resolve_p2p_dispute FROM PUBLIC, anon, authenticated;
@@ -0,0 +1,280 @@
-- Repair: recreate functions that their migrations recorded but never created.
--
-- supabase_migrations.schema_migrations lists 20241211092900 as applied, and its
-- tables (p2p_merchant_tiers, p2p_merchant_stats, p2p_tier_requirements) do
-- exist — but none of its functions do. The same is true of five other
-- migrations: the tables landed, the function bodies did not. Those files carry
-- "Run this in Supabase SQL Editor" headers, so they were pasted in by hand
-- before apply-migrations.sh existed, and a run that stopped partway still got
-- recorded as applied. The CI runner then skipped them forever after.
--
-- This is forward-only repair rather than a re-run of those files. Re-running
-- them would abort on their bare CREATE POLICY/INDEX/TRIGGER statements, since
-- the tables are already there.
--
-- 25 declared functions are missing. Only the ones the app actually reaches are
-- restored here:
-- apply_for_tier_upgrade - MerchantApplication.tsx:213
-- check_tier_eligibility - called by the above
-- update_p2p_reputation - shared/lib/p2p-fiat.ts:803
-- All are CREATE OR REPLACE, so this file is safe to run repeatedly, and every
-- table they touch was verified present first.
--
-- Deliberately NOT re-running the source migrations. 20241117054602 is
-- self-consistent, but 016 later redefined its cancel_expired_trades; replaying
-- the whole file would overwrite the newer definition with the older one. Taking
-- only the missing body avoids that.
--
-- The remaining 22 are left alone: nothing calls them, and several are trigger
-- bodies whose triggers were never created either, so creating them would switch
-- on behaviour that has never run rather than restore something broken. They are
-- listed in deploy/known-schema-gaps.txt.
CREATE OR REPLACE FUNCTION public.check_tier_eligibility(
p_user_id UUID,
p_target_tier VARCHAR(20)
) RETURNS TABLE(
eligible BOOLEAN,
missing_requirements TEXT[]
) AS $$
DECLARE
v_reputation RECORD;
v_stats RECORD;
v_requirements RECORD;
v_missing TEXT[] := '{}';
BEGIN
-- Get requirements
SELECT * INTO v_requirements
FROM public.p2p_tier_requirements
WHERE tier = p_target_tier;
IF NOT FOUND THEN
eligible := FALSE;
missing_requirements := ARRAY['Invalid tier'];
RETURN NEXT;
RETURN;
END IF;
-- Get user reputation
SELECT * INTO v_reputation
FROM public.p2p_reputation
WHERE user_id = p_user_id;
-- Get user stats
SELECT * INTO v_stats
FROM public.p2p_merchant_stats
WHERE user_id = p_user_id;
-- Check completed trades
IF COALESCE(v_reputation.completed_trades, 0) < v_requirements.min_trades THEN
v_missing := array_append(v_missing,
format('Need %s completed trades (have %s)',
v_requirements.min_trades,
COALESCE(v_reputation.completed_trades, 0)));
END IF;
-- Check completion rate
IF COALESCE(v_stats.completion_rate_30d, 0) < v_requirements.min_completion_rate THEN
v_missing := array_append(v_missing,
format('Need %s%% completion rate (have %s%%)',
v_requirements.min_completion_rate,
COALESCE(v_stats.completion_rate_30d, 0)));
END IF;
-- Check 30-day volume
IF COALESCE(v_stats.total_volume_30d, 0) < v_requirements.min_volume_30d THEN
v_missing := array_append(v_missing,
format('Need $%s 30-day volume (have $%s)',
v_requirements.min_volume_30d,
COALESCE(v_stats.total_volume_30d, 0)));
END IF;
-- Check deposit requirement
IF v_requirements.deposit_required > 0 THEN
v_missing := array_append(v_missing,
format('Deposit of %s %s required',
v_requirements.deposit_required,
v_requirements.deposit_token));
END IF;
eligible := array_length(v_missing, 1) IS NULL OR array_length(v_missing, 1) = 0;
missing_requirements := v_missing;
RETURN NEXT;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE OR REPLACE FUNCTION public.apply_for_tier_upgrade(
p_user_id UUID,
p_target_tier VARCHAR(20)
) RETURNS TABLE(
success BOOLEAN,
message TEXT
) AS $$
DECLARE
v_eligibility RECORD;
v_current_tier RECORD;
BEGIN
-- Check current tier
SELECT * INTO v_current_tier
FROM public.p2p_merchant_tiers
WHERE user_id = p_user_id;
-- Check if already at or above target tier
IF v_current_tier IS NOT NULL THEN
IF v_current_tier.tier = p_target_tier THEN
success := FALSE;
message := 'You are already at this tier';
RETURN NEXT;
RETURN;
END IF;
IF v_current_tier.application_status = 'pending' THEN
success := FALSE;
message := 'You already have a pending application';
RETURN NEXT;
RETURN;
END IF;
END IF;
-- Check eligibility
SELECT * INTO v_eligibility
FROM public.check_tier_eligibility(p_user_id, p_target_tier);
IF NOT v_eligibility.eligible THEN
success := FALSE;
message := 'Not eligible: ' || array_to_string(v_eligibility.missing_requirements, ', ');
RETURN NEXT;
RETURN;
END IF;
-- Create or update application
INSERT INTO public.p2p_merchant_tiers (
user_id, application_status, applied_at, applied_for_tier
) VALUES (
p_user_id, 'pending', NOW(), p_target_tier
)
ON CONFLICT (user_id) DO UPDATE SET
application_status = 'pending',
applied_at = NOW(),
applied_for_tier = p_target_tier,
updated_at = NOW();
success := TRUE;
message := 'Application submitted successfully';
RETURN NEXT;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION public.check_tier_eligibility TO authenticated;
GRANT EXECUTE ON FUNCTION public.apply_for_tier_upgrade TO authenticated;
CREATE OR REPLACE FUNCTION public.update_p2p_reputation(
p_seller_id UUID,
p_buyer_id UUID,
p_trade_id UUID
) RETURNS void AS $$
DECLARE
v_trade RECORD;
v_payment_time_minutes INT;
v_confirmation_time_minutes INT;
BEGIN
-- Get trade details
SELECT * INTO v_trade
FROM public.p2p_fiat_trades
WHERE id = p_trade_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'Trade % not found', p_trade_id;
END IF;
-- Calculate timing metrics
IF v_trade.buyer_marked_paid_at IS NOT NULL THEN
v_payment_time_minutes := EXTRACT(EPOCH FROM (v_trade.buyer_marked_paid_at - v_trade.created_at)) / 60;
END IF;
IF v_trade.seller_confirmed_at IS NOT NULL AND v_trade.buyer_marked_paid_at IS NOT NULL THEN
v_confirmation_time_minutes := EXTRACT(EPOCH FROM (v_trade.seller_confirmed_at - v_trade.buyer_marked_paid_at)) / 60;
END IF;
-- Update seller reputation
INSERT INTO public.p2p_reputation (
user_id,
total_trades,
completed_trades,
total_as_seller,
reputation_score,
avg_confirmation_time_minutes,
last_trade_at,
first_trade_at
) VALUES (
p_seller_id,
1,
1,
1,
105, -- +5 bonus for first trade
v_confirmation_time_minutes,
NOW(),
NOW()
)
ON CONFLICT (user_id) DO UPDATE SET
total_trades = p2p_reputation.total_trades + 1,
completed_trades = p2p_reputation.completed_trades + 1,
total_as_seller = p2p_reputation.total_as_seller + 1,
reputation_score = LEAST(p2p_reputation.reputation_score + 5, 1000),
avg_confirmation_time_minutes = CASE
WHEN p2p_reputation.avg_confirmation_time_minutes IS NULL THEN v_confirmation_time_minutes
ELSE (p2p_reputation.avg_confirmation_time_minutes + COALESCE(v_confirmation_time_minutes, 0)) / 2
END,
last_trade_at = NOW(),
updated_at = NOW();
-- Update buyer reputation
INSERT INTO public.p2p_reputation (
user_id,
total_trades,
completed_trades,
total_as_buyer,
reputation_score,
avg_payment_time_minutes,
last_trade_at,
first_trade_at
) VALUES (
p_buyer_id,
1,
1,
1,
105,
v_payment_time_minutes,
NOW(),
NOW()
)
ON CONFLICT (user_id) DO UPDATE SET
total_trades = p2p_reputation.total_trades + 1,
completed_trades = p2p_reputation.completed_trades + 1,
total_as_buyer = p2p_reputation.total_as_buyer + 1,
reputation_score = LEAST(p2p_reputation.reputation_score + 5, 1000),
avg_payment_time_minutes = CASE
WHEN p2p_reputation.avg_payment_time_minutes IS NULL THEN v_payment_time_minutes
ELSE (p2p_reputation.avg_payment_time_minutes + COALESCE(v_payment_time_minutes, 0)) / 2
END,
last_trade_at = NOW(),
updated_at = NOW();
-- Update trust levels based on reputation score
UPDATE public.p2p_reputation
SET trust_level = CASE
WHEN reputation_score >= 900 THEN 'verified'
WHEN reputation_score >= 700 THEN 'advanced'
WHEN reputation_score >= 400 THEN 'intermediate'
WHEN reputation_score >= 100 THEN 'basic'
ELSE 'new'
END,
fast_trader = CASE
WHEN avg_payment_time_minutes < 15 AND avg_confirmation_time_minutes < 30 THEN true
ELSE false
END
WHERE user_id IN (p_seller_id, p_buyer_id);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION public.update_p2p_reputation TO authenticated;
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
# Archived migrations
Superseded by `../00000000000000_baseline.sql` on 2026-08-01. Kept, not deleted:
they are the only record of why parts of the schema look the way they do, even
where they no longer describe it.
**Do not run these.** They are not a working migration set and several are unsafe
to replay.
## Why they were replaced
These files were applied by hand through the Supabase SQL editor over months —
most still carry `-- Run this in Supabase SQL Editor` headers. Some runs stopped
partway and were recorded as applied regardless, so the recorded history stopped
matching the database. Three things made that concrete:
**Functions declared but absent.** 25 functions across six migrations, all marked
applied, did not exist in the database. Their tables did. Two were reached by the
app, so merchant tier upgrades and post-trade reputation updates had been quietly
dead. Found on 2026-07-30 only because a user hit
`Could not find the function public.upsert_user_profile(...)` while toggling a
notification setting.
**Conflicting definitions.** `admin_roles` is defined three different ways and
production matches none of them:
| source | columns |
|---|---|
| `001_initial_schema.sql` | id, user_id, role, granted_by, granted_at |
| `COMBINED_p2p_full_system.sql` | user_id, role, created_at |
| production | id, user_id, role, permissions, created_at, updated_at |
**Not replayable.** Applied to an empty database, five of them fail. The legacy
`0NN` filenames sort before the 14-digit timestamps they depend on — `"013"` <
`"20241117054600"` — so `013` runs before the migration that creates the table it
alters. That ordering could never have worked from scratch.
## What replaced them
A `pg_dump` of the live `public` schema, which matches production by
construction. Verified: applying it to an empty database produces 83 tables, 39
functions, 222 indexes and 360 policies — identical counts to production.
CI now applies migrations to an empty Postgres on every PR, so a migration that
cannot run from scratch fails there instead of on the production host. That check
was impossible while this set was the starting point.
## If you need something from here
Read it, take the statement you need, and write a new forward migration against
the baseline. Do not re-run the file — `20241117054601` inserts payment methods
with no `ON CONFLICT`, `015` has 17 unguarded inserts, and `018` overwrites the
live hot wallet address.