Referral System
Overview
The Med.Fun referral system allows users to earn passive income by inviting friends to the platform. Users receive commission on their referrals' trading volume, with rates increasing based on tier progression.
How It Works
Generate Code: User generates a unique 6-character referral code (or custom code)
Share Link: User shares referral link:
https://med.fun/ref/{CODE}Friend Signs Up: New user creates account using the referral link
Track Activity: System tracks referred user's trading volume
Earn Commission: Referrer earns percentage of trading fees
Claim Earnings: Accumulated earnings can be claimed (min $1.00)
Database Schema
referral_codes
referral_codesStores user referral codes and tracking data.
id
uuid
No
gen_random_uuid()
Primary key
code
text
No
-
Referral code (6-9 chars)
user_wallet
text
No
-
Owner's wallet address
is_custom
boolean
No
false
Whether code is custom
total_referrals
integer
No
0
Count of referrals
total_volume
numeric
No
0
Total trading volume
total_earnings
numeric
No
0
Total commissions earned
created_at
timestamptz
No
now()
Creation timestamp
updated_at
timestamptz
No
now()
Last update timestamp
Constraints:
Unique index on
code(case-insensitive)Unique index on
user_walletCheck:
length(code) >= 1 AND length(code) <= 9
RLS Policies:
Users can view their own codes
Users can create codes for themselves
Users can update their own codes
user_referrals
user_referralsTracks individual referred users and their activity.
id
uuid
No
gen_random_uuid()
Primary key
referrer_wallet
text
No
-
Referrer's wallet
referred_wallet
text
No
-
Referred user's wallet
referral_code
text
No
-
Code used
status
text
No
'active'
Status (active/inactive)
total_volume
numeric
No
0
Referred user's volume
total_earnings
numeric
No
0
Earnings from this user
created_at
timestamptz
No
now()
Referral timestamp
last_trade_at
timestamptz
Yes
null
Last trade timestamp
Constraints:
Unique constraint on
referred_walletForeign key to
referral_codes(code)
RLS Policies:
Users can view their own referrals
System can insert new referrals
referral_earnings
referral_earningsRecords individual commission payments.
id
uuid
No
gen_random_uuid()
Primary key
referrer_wallet
text
No
-
Earner's wallet
referred_wallet
text
No
-
Source user's wallet
amount
numeric
No
-
Commission amount
trade_volume
numeric
No
-
Trade that generated it
commission_rate
numeric
No
-
Rate applied
status
text
No
'pending'
pending/claimed
created_at
timestamptz
No
now()
Earned timestamp
claimed_at
timestamptz
Yes
null
Claimed timestamp
RLS Policies:
Users can view their own earnings
Users can update their own earnings (claim)
referral_tiers
referral_tiersDefines tier structure and benefits.
id
uuid
No
gen_random_uuid()
Primary key
tier_name
text
No
-
Tier name
tier_level
integer
No
-
Tier number (1-4)
min_referrals
integer
No
0
Min referrals needed
min_volume
numeric
No
0
Min volume needed
commission_rate
numeric
No
-
Commission %
benefits
jsonb
No
{}
Tier benefits
color
text
No
-
UI color
created_at
timestamptz
No
now()
Creation timestamp
Default Tiers:
Bronze
1
0
$0
10%
Base commission
Silver
2
5
$1,000
12%
Priority support, Custom codes
Gold
3
25
$10,000
15%
Custom badge, Early access
Platinum
4
100
$100,000
20%
VIP support, Account manager
referral_settings
referral_settingsUser preferences for referral notifications.
id
uuid
No
gen_random_uuid()
Primary key
user_wallet
text
No
-
User's wallet
email_notifications
boolean
No
true
Email notifications
push_notifications
boolean
No
true
Push notifications
auto_claim_threshold
numeric
Yes
null
Auto-claim amount
created_at
timestamptz
No
now()
Creation timestamp
updated_at
timestamptz
No
now()
Last update timestamp
Referral Code System
Auto-Generated Codes
Format: 6 uppercase alphanumeric characters
Example:
ABC123,XYZ789Generation: Random using
Math.random()and character setValidation: Must be unique across all users
Custom Codes
Format: 1-9 alphanumeric characters
Example:
CRYPTO,MOON,TRADERValidation:
Must be 1-9 characters
Alphanumeric only (A-Z, 0-9)
Case-insensitive uniqueness check
Cannot contain special characters
Availability: Check via database before creation
Referral Link Format
Commission Structure
Base Commission
Default Rate: 10% of referred user's trading fees
Calculation:
tradingFee * commissionRateTracking: Real-time per trade
Accumulation: Added to pending earnings
Tier-Based Boosts
Commission rates increase with tier:
Example Calculation
Tier Progression
Tier Requirements
Bronze (Starting Tier)
Min Referrals: 0
Min Volume: $0
Benefits: Base 10% commission
Silver Tier
Min Referrals: 5 active referrals
Min Volume: $1,000 total
Benefits: 12% commission, Priority support, Custom referral codes
Gold Tier
Min Referrals: 25 active referrals
Min Volume: $10,000 total
Benefits: 15% commission, Custom badge, Early access to features
Platinum Tier
Min Referrals: 100 active referrals
Min Volume: $100,000 total
Benefits: 20% commission, VIP support, Dedicated account manager
Tier Calculation Logic
Progress Tracking
Claiming Earnings
Claim Requirements
Minimum Amount: $1.00 USD
Status: Must be 'pending'
User Action: Manual claim via dashboard
Claim Process
Transaction Flow
User clicks "Claim Earnings" button
Frontend validates minimum amount
Backend updates earnings records
Status changes:
pending→claimedclaimed_attimestamp recordedUI updates with new balances
Real-time Updates
Supabase Subscriptions
Referral Updates:
Earnings Updates:
Frontend Components
useReferrals Hook
useReferrals HookLocation: /src/hooks/useReferrals.tsx
Purpose: Manages all referral data and operations
State Management:
Key Functions:
generateReferralCode:
claimEarnings:
copyReferralLink:
ReferralDashboard Component
ReferralDashboard ComponentLocation: /src/components/ReferralDashboard.tsx
Features:
Tabbed interface (Overview, Referrals, Settings)
Referral code display and generation
Link sharing (copy + native share API)
Earnings summary with claim button
Referral list with status and earnings
Tier progress visualization
Mobile-responsive (Sheet on mobile, Dialog on desktop)
UI Structure:
ReferralStatsCard Component
ReferralStatsCard ComponentLocation: /src/components/ReferralStatsCard.tsx
Purpose: Summary card showing key metrics
Displayed Data:
Active referrals count
Total earnings
Pending earnings
"View Details" button
Integration Points
User Signup Flow
Trade Commission Tracking
User Flows
Flow 1: Generate and Share Code
Flow 2: Earn Commission
Flow 3: Claim Earnings
Flow 4: Tier Progression
API Reference
Database Functions
(None currently - all logic in application layer)
RLS Helper Functions
Best Practices
For Developers
1. Always validate referral codes:
2. Use transactions for multi-step operations:
3. Handle race conditions:
4. Monitor real-time subscriptions:
For Product
1. Minimum payout prevents micro-transactions
$1.00 minimum balances gas costs and prevents spam
2. Tier system encourages growth
Progressive rewards incentivize user acquisition
3. Real-time updates build trust
Instant feedback on earnings creates positive UX
4. Custom codes enable branding
Personal codes improve conversion rates
Troubleshooting
Code Already Exists
Error: "Referral code already taken" Solution: Try a different custom code or use auto-generated code
Earnings Not Appearing
Check:
Is referred user's account active?
Has referred user completed trades?
Check database for pending earnings
Verify real-time subscription is active
Cannot Claim Earnings
Check:
Is pending balance >= $1.00?
Are earnings in 'pending' status?
Check wallet connection
Verify RLS policies allow update
Tier Not Updating
Check:
Verify referral count meets minimum
Verify volume meets minimum
Check tier calculation logic
Refresh dashboard data
Performance Considerations
Database Indexes
Query Optimization
Use
select('*')sparingly, fetch only needed columnsImplement pagination for large referral lists
Cache tier data to reduce database calls
Use database views for complex aggregations
Future Enhancements
Potential Features
Auto-Claim: Automatic claiming at threshold
Leaderboards: Top referrers displayed publicly
Bonus Rewards: Limited-time commission boosts
Team Referrals: Multi-level commission structure
Analytics: Detailed referral performance metrics
Email Notifications: Alerts for new referrals and earnings
Technical Improvements
Edge function for commission calculation
Webhooks for real-time trade notifications
GraphQL API for complex queries
Caching layer for frequently accessed data
Last updated
Was this helpful?