Phase 3: own referral system (sats)
- Referral links carry a random 8 character base32 code (rf_<code>) built from the bot username from getMe. Old ref_<id> links still work but are never shown. - The reward (REFERRAL_REWARD_SATS, old name REFERRAL_REWARD still read) is paid through the ledger once the invited user's first purchase settles, once per invited user, never for self-referrals. - REFERRAL_DAILY_CAP limits what an inviter earns per UTC day; rewards above it wait as pending and are paid on a later day by the billing loop. - /referral shows invited, converted, earned and pending, with Share, Copy link and QR code buttons. The Mini App Me page mirrors it. - Migration 00008: users.ref_code (unique) and referral_rewards, backfilled from earlier referral credits in the ledger. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
123cede7f3
commit
f7ceadc462
@@ -0,0 +1,4 @@
|
||||
package db
|
||||
|
||||
// RefCodeGen lets tests replace the referral code generator.
|
||||
var RefCodeGen = &refCodeGen
|
||||
@@ -0,0 +1,33 @@
|
||||
-- +goose Up
|
||||
-- Referral links carry a random code instead of the inviter's Telegram ID.
|
||||
-- A user gets a code the first time they need one; '' means none yet.
|
||||
ALTER TABLE users ADD COLUMN ref_code TEXT NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX users_ref_code_idx ON users (ref_code) WHERE ref_code <> '';
|
||||
|
||||
-- One row per invited user who settled a first Lightning purchase: the
|
||||
-- reward their inviter earned for it. The primary key makes it one reward
|
||||
-- per invited user, ever. A reward over the inviter's daily cap waits as
|
||||
-- 'pending' and is paid (credited through the ledger) on a later day.
|
||||
CREATE TABLE referral_rewards (
|
||||
invitee_id BIGINT PRIMARY KEY,
|
||||
referrer_id BIGINT NOT NULL,
|
||||
purchase_id TEXT NOT NULL DEFAULT '',
|
||||
amount BIGINT NOT NULL,
|
||||
status TEXT NOT NULL, -- paid or pending
|
||||
paid_day INTEGER NOT NULL DEFAULT 0, -- YYYYMMDD (UTC) it was paid on
|
||||
created_at BIGINT NOT NULL,
|
||||
paid_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX referral_rewards_referrer_idx ON referral_rewards (referrer_id, status, paid_day);
|
||||
CREATE INDEX referral_rewards_pending_idx ON referral_rewards (status, created_at);
|
||||
|
||||
-- Rewards paid before this table existed are in the ledger.
|
||||
INSERT INTO referral_rewards (invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at)
|
||||
SELECT CAST(l.ref AS BIGINT), w.owner_id, '', l.amount, 'paid', 0, l.created_at, l.created_at
|
||||
FROM ledger l JOIN wallets w ON w.id = l.wallet_id
|
||||
WHERE l.reason = 'referral' AND w.owner_type = 'user' AND l.ref <> '';
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE referral_rewards;
|
||||
DROP INDEX users_ref_code_idx;
|
||||
ALTER TABLE users DROP COLUMN ref_code;
|
||||
@@ -334,6 +334,12 @@ func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Pur
|
||||
}
|
||||
|
||||
// CountPaidPurchases counts the paid purchases of a user, donations aside.
|
||||
// CountReferralPurchases counts the settled purchases of a user that our
|
||||
// referral program looks at: everything but donations, paid in sats.
|
||||
func (s *Store) CountReferralPurchases(ctx context.Context, userID int64) (int, error) {
|
||||
return s.CountPaidPurchases(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) {
|
||||
var n int
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid'
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base32"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RefCodeLength is the length of a referral code.
|
||||
const RefCodeLength = 8
|
||||
|
||||
// NewRefCode makes a random referral code: 8 characters of RFC 4648
|
||||
// base32 (A to Z, 2 to 7), 40 random bits.
|
||||
func NewRefCode() string {
|
||||
var b [5]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(err) // the system has no randomness; nothing is safe then
|
||||
}
|
||||
return base32.StdEncoding.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// ValidRefCode reports whether s has the shape of a referral code.
|
||||
func ValidRefCode(s string) bool {
|
||||
if len(s) != RefCodeLength {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if !(r >= 'A' && r <= 'Z' || r >= '2' && r <= '7') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// refCodeGen makes codes; tests replace it to force collisions.
|
||||
var refCodeGen = NewRefCode
|
||||
|
||||
// RefCode returns the user's referral code, creating it on first use. A
|
||||
// collision with another user's code, which is rare with 40 bits, is
|
||||
// retried with a new code.
|
||||
func (s *Store) RefCode(ctx context.Context, userID int64) (string, error) {
|
||||
for attempt := 0; attempt < 8; attempt++ {
|
||||
var code string
|
||||
if err := s.row(ctx, `SELECT ref_code FROM users WHERE id = ?`, userID).Scan(&code); err != nil {
|
||||
return "", notFound(err)
|
||||
}
|
||||
if code != "" {
|
||||
return code, nil
|
||||
}
|
||||
_, err := s.exec(ctx, `UPDATE users SET ref_code = ? WHERE id = ? AND ref_code = ''`, refCodeGen(), userID)
|
||||
if err != nil && !isUniqueViolation(err) {
|
||||
return "", err
|
||||
}
|
||||
// Either it was stored, or another request stored one first, or the
|
||||
// code was taken: read again.
|
||||
}
|
||||
return "", errors.New("db: no free referral code")
|
||||
}
|
||||
|
||||
// UserByRefCode finds the owner of a referral code. Codes are compared
|
||||
// in upper case, since some apps change the case of links.
|
||||
func (s *Store) UserByRefCode(ctx context.Context, code string) (*User, error) {
|
||||
code = strings.ToUpper(code)
|
||||
if !ValidRefCode(code) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE ref_code = ?`, code))
|
||||
}
|
||||
|
||||
// Reward statuses.
|
||||
const (
|
||||
RewardPaid = "paid"
|
||||
RewardPending = "pending"
|
||||
)
|
||||
|
||||
// ReferralReward is the reward an inviter earned for one invited user.
|
||||
type ReferralReward struct {
|
||||
InviteeID int64
|
||||
ReferrerID int64
|
||||
PurchaseID string
|
||||
Amount int64
|
||||
Status string
|
||||
PaidDay int
|
||||
CreatedAt int64
|
||||
PaidAt int64
|
||||
}
|
||||
|
||||
// AddReferralReward records a reward. It reports false when the invited
|
||||
// user already earned their inviter a reward.
|
||||
func (s *Store) AddReferralReward(ctx context.Context, r *ReferralReward) (bool, error) {
|
||||
n, err := s.exec(ctx, `INSERT INTO referral_rewards (invitee_id, referrer_id, purchase_id, amount, status,
|
||||
paid_day, created_at, paid_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (invitee_id) DO NOTHING`,
|
||||
r.InviteeID, r.ReferrerID, r.PurchaseID, r.Amount, r.Status, r.PaidDay, r.CreatedAt, r.PaidAt)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// MarkRewardPaid moves a pending reward to paid. It reports false when it
|
||||
// was not pending, so a reward is paid once.
|
||||
func (s *Store) MarkRewardPaid(ctx context.Context, inviteeID int64, day int, now int64) (bool, error) {
|
||||
n, err := s.exec(ctx, `UPDATE referral_rewards SET status = 'paid', paid_day = ?, paid_at = ?
|
||||
WHERE invitee_id = ? AND status = 'pending'`, day, now, inviteeID)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// RewardsPaidOn sums what an inviter was paid in rewards on a day.
|
||||
func (s *Store) RewardsPaidOn(ctx context.Context, referrerID int64, day int) (int64, error) {
|
||||
var n int64
|
||||
err := s.row(ctx, `SELECT COALESCE(SUM(amount), 0) FROM referral_rewards
|
||||
WHERE referrer_id = ? AND status = 'paid' AND paid_day = ?`, referrerID, day).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// PendingRewards lists rewards waiting for their inviter's daily cap,
|
||||
// oldest first.
|
||||
func (s *Store) PendingRewards(ctx context.Context, limit int) ([]ReferralReward, error) {
|
||||
rows, err := s.rows(ctx, `SELECT invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at
|
||||
FROM referral_rewards WHERE status = 'pending' ORDER BY created_at, invitee_id LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ReferralReward
|
||||
for rows.Next() {
|
||||
var r ReferralReward
|
||||
if err := rows.Scan(&r.InviteeID, &r.ReferrerID, &r.PurchaseID, &r.Amount, &r.Status, &r.PaidDay, &r.CreatedAt, &r.PaidAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ReferralStats is what /referral shows an inviter.
|
||||
type ReferralStats struct {
|
||||
Invited int // users who joined through their link
|
||||
Converted int // of those, users who settled a first purchase
|
||||
Earned int64 // sats paid out
|
||||
Pending int64 // sats earned, waiting for the daily cap
|
||||
}
|
||||
|
||||
// ReferralStatsFor sums up an inviter's referrals.
|
||||
func (s *Store) ReferralStatsFor(ctx context.Context, referrerID int64) (ReferralStats, error) {
|
||||
var st ReferralStats
|
||||
if err := s.row(ctx, `SELECT COUNT(*) FROM users WHERE referred_by = ?`, referrerID).Scan(&st.Invited); err != nil {
|
||||
return st, err
|
||||
}
|
||||
err := s.row(ctx, `SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), 0),
|
||||
COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0)
|
||||
FROM referral_rewards WHERE referrer_id = ?`, referrerID).Scan(&st.Converted, &st.Earned, &st.Pending)
|
||||
return st, err
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/db/dbtest"
|
||||
)
|
||||
|
||||
func TestRefCodesAreShortRandomAndUnique(t *testing.T) {
|
||||
store := dbtest.Open(t).Store()
|
||||
ctx := context.Background()
|
||||
seen := map[string]bool{}
|
||||
for id := int64(1); id <= 300; id++ {
|
||||
if _, err := store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := store.RefCode(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !db.ValidRefCode(code) {
|
||||
t.Fatalf("code %q is not 8 characters of base32", code)
|
||||
}
|
||||
if seen[code] {
|
||||
t.Fatalf("code %q given twice", code)
|
||||
}
|
||||
seen[code] = true
|
||||
// The code is stable once made.
|
||||
if again, _ := store.RefCode(ctx, id); again != code {
|
||||
t.Fatalf("code changed from %q to %q", code, again)
|
||||
}
|
||||
owner, err := store.UserByRefCode(ctx, code)
|
||||
if err != nil || owner.ID != id {
|
||||
t.Fatalf("UserByRefCode(%q) = %+v, %v", code, owner, err)
|
||||
}
|
||||
}
|
||||
// Lower case works (some apps change links), garbage does not.
|
||||
for code := range seen {
|
||||
lower := []byte(code)
|
||||
for i, c := range lower {
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
lower[i] = c + 32
|
||||
}
|
||||
}
|
||||
if _, err := store.UserByRefCode(ctx, string(lower)); err != nil {
|
||||
t.Fatalf("lower case code: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
for _, bad := range []string{"", "ABC", "ABCDEFG1", "ABCDEFGHI", "12345678", "' OR 1=1"} {
|
||||
if _, err := store.UserByRefCode(ctx, bad); err != db.ErrNotFound {
|
||||
t.Errorf("UserByRefCode(%q) = %v, want not found", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefCodeCollisionIsRetried(t *testing.T) {
|
||||
store := dbtest.Open(t).Store()
|
||||
ctx := context.Background()
|
||||
for _, id := range []int64{1, 2} {
|
||||
if _, err := store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
codes := []string{"AAAAAAAA", "AAAAAAAA", "BBBBBBBB"}
|
||||
restore := *db.RefCodeGen
|
||||
*db.RefCodeGen = func() string { c := codes[0]; codes = codes[1:]; return c }
|
||||
defer func() { *db.RefCodeGen = restore }()
|
||||
first, err := store.RefCode(ctx, 1)
|
||||
if err != nil || first != "AAAAAAAA" {
|
||||
t.Fatalf("first = %q, %v", first, err)
|
||||
}
|
||||
// The second user draws the same code first, then a free one.
|
||||
second, err := store.RefCode(ctx, 2)
|
||||
if err != nil || second != "BBBBBBBB" {
|
||||
t.Fatalf("second = %q, %v", second, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user