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:
Michilis
2026-11-18 20:58:43 +00:00
co-authored by Claude Opus 5.5
parent 123cede7f3
commit f7ceadc462
30 changed files with 945 additions and 148 deletions
+99 -8
View File
@@ -497,35 +497,119 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
return true, nil
}
// rewardReferrer credits the inviter on the invited user's first real
// purchase. The dedupe key allows one reward per invited user, ever.
// rewardReferrer pays the inviter of a user who settled their first
// purchase. Our referral program covers Lightning purchases only:
// purchases paid in Telegram Stars earn affiliates a commission through
// Telegram's own affiliate program, so paying sats for them as well would
// reward the same purchase twice. Donations are not purchases.
//
// The reward is recorded once per invited user (the referral_rewards key)
// and credited through the ledger with a dedupe key. Over the inviter's
// daily cap it is recorded as pending and paid by PayPendingReferrals on
// a later day.
func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purchase, now int64) error {
reward := b.cfg.Prices.ReferralReward
if reward <= 0 || p.Product == ProductDonation {
if reward <= 0 || p.Product == ProductDonation || !countsForReferral(p) {
return nil
}
u, err := tx.GetUser(ctx, p.UserID)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil || u.ReferredBy == 0 {
if err != nil || u.ReferredBy == 0 || u.ReferredBy == u.ID {
return err
}
n, err := tx.CountPaidPurchases(ctx, p.UserID)
n, err := tx.CountReferralPurchases(ctx, p.UserID)
if err != nil || n != 1 {
return err // not the first one
}
day := utcDay(time.UnixMilli(now))
r := &db.ReferralReward{
InviteeID: p.UserID, ReferrerID: u.ReferredBy, PurchaseID: p.ID, Amount: reward,
Status: db.RewardPending, CreatedAt: now,
}
ok, err := b.underCap(ctx, tx, u.ReferredBy, day, reward)
if err != nil {
return err
}
w, err := tx.EnsureWallet(ctx, db.OwnerUser, u.ReferredBy)
if ok {
r.Status, r.PaidDay, r.PaidAt = db.RewardPaid, day, now
}
added, err := tx.AddReferralReward(ctx, r)
if err != nil || !added || r.Status != db.RewardPaid {
return err
}
return b.creditReward(ctx, tx, r, now)
}
// countsForReferral reports whether a purchase was paid in a way our
// referral program rewards: Lightning.
func countsForReferral(p *db.Purchase) bool { return true }
// underCap reports whether an inviter may be paid amount more today.
func (b *Billing) underCap(ctx context.Context, tx *db.Store, referrer int64, day int, amount int64) (bool, error) {
limit := b.cfg.ReferralDailyCap
if limit <= 0 {
return true, nil
}
paid, err := tx.RewardsPaidOn(ctx, referrer, day)
return paid+amount <= limit, err
}
func (b *Billing) creditReward(ctx context.Context, tx *db.Store, r *db.ReferralReward, now int64) error {
w, err := tx.EnsureWallet(ctx, db.OwnerUser, r.ReferrerID)
if err != nil {
return err
}
_, err = tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: w.ID, Kind: db.LedgerCredit, Amount: reward, Reason: "referral",
Ref: fmt.Sprint(p.UserID), DedupeKey: fmt.Sprintf("referral:%d", p.UserID), CreatedAt: now,
WalletID: w.ID, Kind: db.LedgerCredit, Amount: r.Amount, Reason: "referral",
Ref: fmt.Sprint(r.InviteeID), DedupeKey: fmt.Sprintf("referral:%d", r.InviteeID), CreatedAt: now,
})
return err
}
// PayPendingReferrals pays rewards that waited for their inviter's daily
// cap, as far as today's cap allows, oldest first. It returns how many it
// paid. Each one moves from pending to paid and is credited in one
// transaction, so running it twice pays nothing twice.
func (b *Billing) PayPendingReferrals(ctx context.Context) (int, error) {
list, err := b.store.PendingRewards(ctx, 200)
if err != nil {
return 0, err
}
paid := 0
for _, r := range list {
r := r
err := b.store.InTx(ctx, func(tx *db.Store) error {
now := b.nowMilli()
day := utcDay(time.UnixMilli(now))
ok, err := b.underCap(ctx, tx, r.ReferrerID, day, r.Amount)
if err != nil || !ok {
return err
}
won, err := tx.MarkRewardPaid(ctx, r.InviteeID, day, now)
if err != nil || !won {
return err
}
if err := b.creditReward(ctx, tx, &r, now); err != nil {
return err
}
paid++
return nil
})
if err != nil && !errors.Is(err, db.ErrDuplicate) {
return paid, err
}
}
return paid, nil
}
// utcDay is a day as YYYYMMDD in UTC.
func utcDay(t time.Time) int {
y, m, d := t.UTC().Date()
return y*10000 + int(m)*100 + d
}
// Cancel closes a pending purchase on the payer's request. If the invoice
// is paid anyway, the payment is still credited when it is detected.
func (b *Billing) Cancel(ctx context.Context, purchaseID string, userID int64) (*db.Purchase, error) {
@@ -641,6 +725,13 @@ func (b *Billing) Run(ctx context.Context) {
if _, err := b.Reconcile(ctx, window); err != nil && ctx.Err() == nil {
b.log.Warn("payment poll failed", "err", err)
}
if tick%12 == 0 {
if n, err := b.PayPendingReferrals(ctx); err != nil && ctx.Err() == nil {
b.log.Warn("paying pending referral rewards failed", "err", err)
} else if n > 0 {
b.log.Info("pending referral rewards paid", "count", n)
}
}
}
}
}
+78
View File
@@ -755,3 +755,81 @@ func TestGrantPassAndState(t *testing.T) {
t.Fatalf("group wallet = %+v, %v", g, err)
}
}
func TestReferralRewardWaitsForSettlementAndTheDailyCap(t *testing.T) {
r := newRig(t)
r.cfg.ReferralDailyCap = 300
r.b = r.newBilling()
ctx := context.Background()
const inviter = int64(600)
invitees := []int64{601, 602, 603}
for _, id := range append([]int64{inviter}, invitees...) {
if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
t.Fatal(err)
}
}
for _, id := range invitees {
if ok, err := r.store.SetReferrer(ctx, id, inviter); err != nil || !ok {
t.Fatalf("SetReferrer: %v %v", ok, err)
}
}
stats := func() db.ReferralStats {
st, err := r.store.ReferralStatsFor(ctx, inviter)
if err != nil {
t.Fatal(err)
}
return st
}
// An invoice that is created but not paid earns nothing.
unpaid := r.buy(invitees[0], billing.ProductPassDay, 0)
if r.balance(inviter) != 0 || stats().Converted != 0 {
t.Fatal("a reward before the payment settled")
}
// Paid: the reward arrives once, however often the webhook comes.
if err := r.ln.Pay(unpaid.PaymentHash); err != nil {
t.Fatal(err)
}
for i := 0; i < 3; i++ {
if err := r.b.HandleWebhook(ctx, unpaid.PaymentHash); err != nil {
t.Fatal(err)
}
}
if got := r.balance(inviter); got != 200 {
t.Fatalf("balance after one settled purchase = %d, want 200", got)
}
// The second reward of the day would pass the 300 sat cap: it waits.
_ = r.ln.Pay(r.buy(invitees[1], billing.ProductCredits, 1000).PaymentHash)
_ = r.ln.Pay(r.buy(invitees[2], billing.ProductCredits, 1000).PaymentHash)
if got := r.balance(inviter); got != 200 {
t.Fatalf("balance over the cap = %d, want 200", got)
}
if st := stats(); st.Invited != 3 || st.Converted != 3 || st.Earned != 200 || st.Pending != 400 {
t.Fatalf("stats = %+v", st)
}
if n, err := r.b.PayPendingReferrals(ctx); err != nil || n != 0 {
t.Fatalf("paid %d pending rewards on the same day (%v)", n, err)
}
// The next day one more fits under the cap, the day after the last.
r.advance(24 * time.Hour)
if n, _ := r.b.PayPendingReferrals(ctx); n != 1 {
t.Fatalf("paid %d the next day, want 1", n)
}
if n, _ := r.b.PayPendingReferrals(ctx); n != 0 {
t.Fatalf("paid %d more on the same day", n)
}
r.advance(24 * time.Hour)
if n, _ := r.b.PayPendingReferrals(ctx); n != 1 {
t.Fatalf("paid %d on the third day, want 1", n)
}
if st := stats(); st.Earned != 600 || st.Pending != 0 || r.balance(inviter) != 600 {
t.Fatalf("at the end: stats %+v, balance %d", st, r.balance(inviter))
}
// Later purchases of the same people earn nothing more.
_ = r.ln.Pay(r.buy(invitees[0], billing.ProductCredits, 1000).PaymentHash)
if r.balance(inviter) != 600 {
t.Fatal("a second purchase was rewarded")
}
r.booksBalance()
}