- Stars as a second payment method for passes and credit packs, next to Lightning (STARS_ENABLED, prices in [stars_prices] / STARS_PRICES, set on their own). Invoices in XTR with no provider token and one price; pre-checkout checks payer, state, currency and amount; successful_payment settles through the same transaction as Lightning, so entitlement is identical. Idempotent by telegram_payment_charge_id (unique index). - Migration 00009: payment_method on purchases and ledger entries, plus stars_amount, tg_charge_id and refunded_at on purchases. Stars purchases never reach LNbits. - Chat: buy screen, /credits, /account and the over-limit offer show Lightning first and a Pay with Stars button. - Mini App: Lightning and Stars switch on Buy; Stars use createInvoiceLink and WebApp.openInvoice, confirmed by the server-side payment event. - Owner /refund <purchase or charge ID> calls refundStarPayment and takes back the credits or pass; refunded_payment messages do the same once. /stats shows revenue by payment method. - The sats referral reward counts Lightning purchases only. - The bot now asks Telegram for pre_checkout_query updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
765 lines
23 KiB
Go
765 lines
23 KiB
Go
// Package billing handles money: wallets, the append-only ledger, passes,
|
|
// invoices and their settlement.
|
|
//
|
|
// Safety rules this package enforces:
|
|
//
|
|
// - A purchase is settled by one conditional UPDATE. However many
|
|
// webhooks and polls race for the same invoice, exactly one wins.
|
|
// - A webhook is only a hint. LNbits webhooks are unsigned, so the
|
|
// payment is always confirmed with LNbits before anything is credited.
|
|
// - Webhooks can be lost (LNbits sends each one once), so unsettled
|
|
// invoices are also polled, and all of them are checked at startup.
|
|
// - A payment that arrives after its invoice was cancelled or expired is
|
|
// still credited. Money received is never dropped.
|
|
package billing
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/noderunners/dlbot/internal/billing/lnbits"
|
|
"github.com/noderunners/dlbot/internal/config"
|
|
"github.com/noderunners/dlbot/internal/db"
|
|
"github.com/noderunners/dlbot/internal/entitle"
|
|
"github.com/noderunners/dlbot/internal/ids"
|
|
)
|
|
|
|
// Products that can be bought.
|
|
const (
|
|
ProductPassDay = "pass_day"
|
|
ProductPassWeek = "pass_week"
|
|
ProductPassMonth = "pass_month"
|
|
ProductCredits = "credits"
|
|
ProductOneOff = "one_off"
|
|
ProductSkipQueue = "skip_queue"
|
|
ProductDonation = "donation"
|
|
)
|
|
|
|
// Products lists every product, for validation and catalog checks.
|
|
var Products = []string{
|
|
ProductPassDay, ProductPassWeek, ProductPassMonth, ProductCredits,
|
|
ProductOneOff, ProductSkipQueue, ProductDonation,
|
|
}
|
|
|
|
// ValidProduct reports whether name is a product that exists.
|
|
func ValidProduct(name string) bool {
|
|
for _, p := range Products {
|
|
if p == name {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Amount bounds for products whose amount the buyer picks.
|
|
const (
|
|
MinAmount = 10
|
|
MaxAmount = 5_000_000
|
|
)
|
|
|
|
// Errors returned by this package.
|
|
var (
|
|
ErrDisabled = errors.New("billing: payments are not configured")
|
|
ErrBadProduct = errors.New("billing: unknown product")
|
|
ErrBadAmount = errors.New("billing: amount out of range")
|
|
ErrNotOwner = errors.New("billing: purchase belongs to another user")
|
|
ErrGiftInvalid = errors.New("billing: gift code is not valid")
|
|
ErrGiftUsed = errors.New("billing: gift code was already used")
|
|
ErrLightningDown = errors.New("billing: lightning backend unreachable")
|
|
)
|
|
|
|
// Lightning is the payment backend. *lnbits.Client implements it.
|
|
type Lightning interface {
|
|
CreateInvoice(ctx context.Context, sats int64, memo string, expiry time.Duration, webhook string) (*lnbits.Invoice, error)
|
|
Paid(ctx context.Context, paymentHash string) (bool, error)
|
|
Health(ctx context.Context) error
|
|
}
|
|
|
|
// EventType says what happened to a purchase.
|
|
type EventType string
|
|
|
|
// The purchase events.
|
|
const (
|
|
EventPaid EventType = "paid"
|
|
EventExpired EventType = "expired"
|
|
EventCancelled EventType = "cancelled"
|
|
)
|
|
|
|
// Event is sent to listeners after the change is committed.
|
|
type Event struct {
|
|
Type EventType
|
|
Purchase *db.Purchase
|
|
}
|
|
|
|
// Billing is the money service.
|
|
type Billing struct {
|
|
store *db.Store
|
|
ln Lightning
|
|
cfg config.Config
|
|
log *slog.Logger
|
|
now func() time.Time
|
|
|
|
mu sync.Mutex
|
|
listeners []func(Event)
|
|
reachable bool
|
|
|
|
stats Stats
|
|
}
|
|
|
|
// Stats are counters for metrics.
|
|
type Stats struct {
|
|
InvoicesCreated int64
|
|
InvoicesSettled int64
|
|
}
|
|
|
|
// New creates the service. ln may be nil, which disables payments while
|
|
// wallets, grants and gift codes keep working.
|
|
func New(store *db.Store, ln Lightning, cfg config.Config, log *slog.Logger) *Billing {
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
return &Billing{store: store, ln: ln, cfg: cfg, log: log, now: time.Now, reachable: ln != nil}
|
|
}
|
|
|
|
// SetClock replaces the time source, for tests.
|
|
func (b *Billing) SetClock(now func() time.Time) { b.now = now }
|
|
|
|
// Enabled reports whether invoices can be created.
|
|
func (b *Billing) Enabled() bool { return b.ln != nil }
|
|
|
|
// Reachable reports whether the last call to the payment backend worked.
|
|
func (b *Billing) Reachable() bool {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.reachable
|
|
}
|
|
|
|
// Stats returns a copy of the counters.
|
|
func (b *Billing) Stats() Stats {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.stats
|
|
}
|
|
|
|
func (b *Billing) setReachable(ok bool) {
|
|
b.mu.Lock()
|
|
b.reachable = ok
|
|
b.mu.Unlock()
|
|
}
|
|
|
|
// Subscribe registers a listener for purchase events. Listeners are called
|
|
// synchronously and must not block.
|
|
func (b *Billing) Subscribe(fn func(Event)) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
b.listeners = append(b.listeners, fn)
|
|
}
|
|
|
|
func (b *Billing) emit(t EventType, p *db.Purchase) {
|
|
b.mu.Lock()
|
|
ls := b.listeners
|
|
b.mu.Unlock()
|
|
for _, fn := range ls {
|
|
fn(Event{Type: t, Purchase: p})
|
|
}
|
|
}
|
|
|
|
func (b *Billing) nowMilli() int64 { return b.now().UnixMilli() }
|
|
|
|
// --- wallets ---------------------------------------------------------------
|
|
|
|
// Wallet returns the wallet of a user or group, creating it when needed.
|
|
func (b *Billing) Wallet(ctx context.Context, ownerType string, ownerID int64) (*db.Wallet, error) {
|
|
return b.store.EnsureWallet(ctx, ownerType, ownerID)
|
|
}
|
|
|
|
// State returns what the entitlement resolver needs to know about an
|
|
// owner's wallet. An owner without a wallet has an empty state.
|
|
func (b *Billing) State(ctx context.Context, ownerType string, ownerID int64) (entitle.Wallet, error) {
|
|
w, err := b.store.FindWallet(ctx, ownerType, ownerID)
|
|
if errors.Is(err, db.ErrNotFound) {
|
|
return entitle.Wallet{}, nil
|
|
}
|
|
if err != nil {
|
|
return entitle.Wallet{}, err
|
|
}
|
|
until, err := b.store.PassUntil(ctx, w.ID, b.nowMilli())
|
|
if err != nil {
|
|
return entitle.Wallet{}, err
|
|
}
|
|
return entitle.Wallet{ID: w.ID, PassUntil: until, Credits: w.Balance}, nil
|
|
}
|
|
|
|
// Credit adds sats to a wallet. The dedupe key makes it idempotent.
|
|
func (b *Billing) Credit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
|
|
return b.move(ctx, db.LedgerCredit, walletID, sats, reason, ref, dedupe, actor, "")
|
|
}
|
|
|
|
// Debit takes sats from a wallet, or fails with db.ErrInsufficient.
|
|
func (b *Billing) Debit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
|
|
return b.move(ctx, db.LedgerDebit, walletID, sats, reason, ref, dedupe, actor, "")
|
|
}
|
|
|
|
// Refund gives sats back to a wallet.
|
|
func (b *Billing) Refund(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
|
|
return b.move(ctx, db.LedgerRefund, walletID, sats, reason, ref, dedupe, actor, "")
|
|
}
|
|
|
|
func (b *Billing) move(ctx context.Context, kind, walletID string, sats int64, reason, ref, dedupe string, actor int64, method string) (bool, error) {
|
|
var applied bool
|
|
err := b.store.InTx(ctx, func(tx *db.Store) error {
|
|
var err error
|
|
applied, err = tx.AddLedger(ctx, &db.LedgerEntry{
|
|
WalletID: walletID, Kind: kind, Amount: sats, Reason: reason, Ref: ref,
|
|
DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(), PaymentMethod: method,
|
|
})
|
|
return err
|
|
})
|
|
if errors.Is(err, db.ErrDuplicate) {
|
|
return false, nil
|
|
}
|
|
return applied, err
|
|
}
|
|
|
|
// PassLength returns how long a pass kind lasts.
|
|
func PassLength(kind string) time.Duration {
|
|
switch kind {
|
|
case "day":
|
|
return 24 * time.Hour
|
|
case "week":
|
|
return 7 * 24 * time.Hour
|
|
case "month":
|
|
return 30 * 24 * time.Hour
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// passKind maps a product to its pass kind, or "".
|
|
func passKind(product string) string {
|
|
switch product {
|
|
case ProductPassDay:
|
|
return "day"
|
|
case ProductPassWeek:
|
|
return "week"
|
|
case ProductPassMonth:
|
|
return "month"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// GrantPass gives a wallet a pass without payment (owner grants, gifts).
|
|
func (b *Billing) GrantPass(ctx context.Context, walletID, kind, source string) (*db.Pass, error) {
|
|
length := PassLength(kind)
|
|
if length == 0 {
|
|
return nil, ErrBadProduct
|
|
}
|
|
var pass *db.Pass
|
|
err := b.store.InTx(ctx, func(tx *db.Store) error {
|
|
var err error
|
|
pass, err = tx.AddPass(ctx, walletID, kind, length.Milliseconds(), source, b.nowMilli())
|
|
return err
|
|
})
|
|
return pass, err
|
|
}
|
|
|
|
// --- purchases -------------------------------------------------------------
|
|
|
|
// Price returns the price in sats of a product. amount is used for the
|
|
// products whose amount the buyer or the caller decides.
|
|
func (b *Billing) Price(product string, amount int64) (int64, error) {
|
|
p := b.cfg.Prices
|
|
switch product {
|
|
case ProductPassDay, ProductPassWeek, ProductPassMonth:
|
|
return p.PassPrice(passKind(product)), nil
|
|
case ProductSkipQueue:
|
|
return p.SkipQueue, nil
|
|
case ProductCredits, ProductDonation, ProductOneOff:
|
|
if amount < MinAmount || amount > MaxAmount {
|
|
return 0, ErrBadAmount
|
|
}
|
|
return amount, nil
|
|
}
|
|
return 0, ErrBadProduct
|
|
}
|
|
|
|
// NewPurchase describes an invoice to create.
|
|
type NewPurchase struct {
|
|
// UserID is the payer. The invoice message goes to their private chat.
|
|
UserID int64
|
|
// WalletID is the wallet that benefits: the payer's or a group's.
|
|
WalletID string
|
|
Product string
|
|
// Amount is required for credits, donations and one-off payments.
|
|
Amount int64
|
|
// Memo is the description shown in the payer's Lightning wallet.
|
|
Memo string
|
|
Lang string
|
|
// RequestID and Profile name a download to start once paid.
|
|
RequestID string
|
|
Profile string
|
|
// DeliveryID names the waiting delivery for a skip-the-queue payment.
|
|
DeliveryID string
|
|
}
|
|
|
|
// CreatePurchase creates a Lightning invoice and records what it is for.
|
|
func (b *Billing) CreatePurchase(ctx context.Context, np NewPurchase) (*db.Purchase, error) {
|
|
if b.ln == nil {
|
|
return nil, ErrDisabled
|
|
}
|
|
price, err := b.Price(np.Product, np.Amount)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if price <= 0 {
|
|
return nil, ErrBadAmount
|
|
}
|
|
expiry := b.cfg.LNbits.InvoiceExpiry.D()
|
|
inv, err := b.ln.CreateInvoice(ctx, price, np.Memo, expiry, b.WebhookURL())
|
|
if err != nil {
|
|
b.setReachable(false)
|
|
b.log.Error("create invoice failed", "product", np.Product, "user_id", np.UserID, "err", err)
|
|
return nil, fmt.Errorf("%w: %v", ErrLightningDown, err)
|
|
}
|
|
b.setReachable(true)
|
|
now := b.nowMilli()
|
|
p := &db.Purchase{
|
|
ID: ids.New(),
|
|
UserID: np.UserID,
|
|
WalletID: np.WalletID,
|
|
Product: np.Product,
|
|
AmountSats: price,
|
|
Status: db.PurchasePending,
|
|
PaymentHash: inv.PaymentHash,
|
|
Bolt11: inv.Bolt11,
|
|
Lang: np.Lang,
|
|
RequestID: np.RequestID,
|
|
Profile: np.Profile,
|
|
DeliveryID: np.DeliveryID,
|
|
CreatedAt: now,
|
|
ExpiresAt: now + expiry.Milliseconds(),
|
|
}
|
|
if err := b.store.InsertPurchase(ctx, p); err != nil {
|
|
return nil, err
|
|
}
|
|
b.mu.Lock()
|
|
b.stats.InvoicesCreated++
|
|
b.mu.Unlock()
|
|
// The payment hash identifies the invoice but is not a secret: it is
|
|
// printed inside every BOLT11 string. The invoice itself is not logged.
|
|
b.log.Info("invoice created", "purchase_id", p.ID, "product", p.Product, "sats", price,
|
|
"user_id", np.UserID, "wallet_id", np.WalletID)
|
|
return p, nil
|
|
}
|
|
|
|
// WebhookURL returns the address LNbits is asked to call, or "" when the
|
|
// core has no public URL. Without it settlement relies on polling.
|
|
func (b *Billing) WebhookURL() string {
|
|
if b.cfg.PublicURL == "" || b.cfg.LNbits.WebhookSecret == "" {
|
|
return ""
|
|
}
|
|
return b.cfg.PublicURL + "/lnbits/webhook/" + b.cfg.LNbits.WebhookSecret
|
|
}
|
|
|
|
// HandleWebhook processes a payment notification. The notification is not
|
|
// trusted: the invoice is looked up by hash and its status is read from
|
|
// LNbits before anything is credited. Unknown hashes are ignored.
|
|
func (b *Billing) HandleWebhook(ctx context.Context, paymentHash string) error {
|
|
p, err := b.store.GetPurchaseByHash(ctx, paymentHash)
|
|
if errors.Is(err, db.ErrNotFound) {
|
|
b.log.Warn("webhook for unknown payment hash")
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = b.checkOne(ctx, p)
|
|
return err
|
|
}
|
|
|
|
// Check asks LNbits about one purchase and settles it when paid. It
|
|
// returns the purchase in its current state.
|
|
func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (*db.Purchase, error) {
|
|
p, err := b.store.GetPurchase(ctx, purchaseID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if p.UserID != userID {
|
|
return nil, ErrNotOwner
|
|
}
|
|
if p.Status != db.PurchasePaid && p.PaymentMethod != db.PayStars {
|
|
// A Stars payment arrives as a Telegram update; there is nothing
|
|
// to ask LNbits about.
|
|
if _, err := b.checkOne(ctx, p); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return b.store.GetPurchase(ctx, purchaseID)
|
|
}
|
|
|
|
// checkOne confirms a purchase with LNbits and settles or expires it.
|
|
func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, err error) {
|
|
if p.Status == db.PurchasePaid || p.PaymentMethod == db.PayStars {
|
|
return false, nil
|
|
}
|
|
if b.ln == nil {
|
|
return false, ErrDisabled
|
|
}
|
|
paid, err := b.ln.Paid(ctx, p.PaymentHash)
|
|
if err != nil {
|
|
if errors.Is(err, lnbits.ErrNotFound) {
|
|
// LNbits does not know the invoice (for example after a wallet
|
|
// reset). It can never be paid, so it only expires.
|
|
paid = false
|
|
} else {
|
|
b.setReachable(false)
|
|
return false, fmt.Errorf("%w: %v", ErrLightningDown, err)
|
|
}
|
|
}
|
|
b.setReachable(true)
|
|
if paid {
|
|
return b.Settle(ctx, p.ID)
|
|
}
|
|
// Only expire after LNbits said "not paid". While LNbits cannot be
|
|
// asked, an invoice stays open rather than risk telling a payer that
|
|
// their paid invoice expired.
|
|
if p.Status == db.PurchasePending && b.nowMilli() > p.ExpiresAt {
|
|
closed, err := b.store.ClosePurchase(ctx, p.ID, db.PurchaseExpired)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if closed {
|
|
p.Status = db.PurchaseExpired
|
|
b.log.Info("invoice expired", "purchase_id", p.ID, "product", p.Product)
|
|
b.emit(EventExpired, p)
|
|
}
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
// Settle marks a purchase as paid and grants what it bought, in one
|
|
// transaction. It is idempotent: the second and later calls return false
|
|
// and change nothing. Callers must have confirmed the payment.
|
|
func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
|
|
settled, _, err := b.settle(ctx, purchaseID, nil)
|
|
return settled, err
|
|
}
|
|
|
|
// settle is Settle with a step of its own inside the transaction, run once
|
|
// the purchase is marked paid: a Stars payment records its charge ID there.
|
|
func (b *Billing) settle(ctx context.Context, purchaseID string, inTx func(tx *db.Store) error) (bool, *db.Purchase, error) {
|
|
var (
|
|
settled bool
|
|
p *db.Purchase
|
|
)
|
|
err := b.store.InTx(ctx, func(tx *db.Store) error {
|
|
now := b.nowMilli()
|
|
won, err := tx.MarkPurchasePaid(ctx, purchaseID, now)
|
|
if err != nil || !won {
|
|
return err
|
|
}
|
|
if inTx != nil {
|
|
if err := inTx(tx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if p, err = tx.GetPurchase(ctx, purchaseID); err != nil {
|
|
return err
|
|
}
|
|
switch {
|
|
case p.Product == ProductCredits:
|
|
if _, err := tx.AddLedger(ctx, &db.LedgerEntry{
|
|
WalletID: p.WalletID, Kind: db.LedgerCredit, Amount: p.AmountSats,
|
|
Reason: "purchase", Ref: p.ID, DedupeKey: "purchase:" + p.ID, ActorID: p.UserID, CreatedAt: now,
|
|
PaymentMethod: p.PaymentMethod,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
case passKind(p.Product) != "":
|
|
kind := passKind(p.Product)
|
|
if _, err := tx.AddPass(ctx, p.WalletID, kind, PassLength(kind).Milliseconds(), p.ID, now); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
// A purchase with nothing to start afterwards is complete here.
|
|
if p.RequestID == "" && p.DeliveryID == "" {
|
|
if _, err := tx.MarkPurchaseFulfilled(ctx, p.ID); err != nil {
|
|
return err
|
|
}
|
|
p.Fulfilled = true
|
|
}
|
|
if err := b.rewardReferrer(ctx, tx, p, now); err != nil {
|
|
return err
|
|
}
|
|
settled = true
|
|
return nil
|
|
})
|
|
if errors.Is(err, db.ErrDuplicate) {
|
|
return false, nil, nil // another connection settled it first
|
|
}
|
|
if err != nil || !settled {
|
|
return false, nil, err
|
|
}
|
|
b.mu.Lock()
|
|
b.stats.InvoicesSettled++
|
|
b.mu.Unlock()
|
|
b.log.Info("invoice settled", "purchase_id", p.ID, "product", p.Product, "sats", p.AmountSats,
|
|
"stars", p.StarsAmount, "method", p.PaymentMethod, "user_id", p.UserID, "wallet_id", p.WalletID)
|
|
b.emit(EventPaid, p)
|
|
return true, p, nil
|
|
}
|
|
|
|
// 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 || !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 || u.ReferredBy == u.ID {
|
|
return err
|
|
}
|
|
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
|
|
}
|
|
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 p.PaymentMethod == db.PayLightning || p.PaymentMethod == ""
|
|
}
|
|
|
|
// 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: 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) {
|
|
p, err := b.store.GetPurchase(ctx, purchaseID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if p.UserID != userID {
|
|
return nil, ErrNotOwner
|
|
}
|
|
closed, err := b.store.ClosePurchase(ctx, p.ID, db.PurchaseCancelled)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if closed {
|
|
p.Status = db.PurchaseCancelled
|
|
b.emit(EventCancelled, p)
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// ConvertToCredits turns a paid purchase that could not deliver what it
|
|
// was for (the job is gone, the card expired) into credits of the same
|
|
// amount on the payer's wallet. Money received is never lost.
|
|
func (b *Billing) ConvertToCredits(ctx context.Context, p *db.Purchase) (bool, error) {
|
|
if p.Status != db.PurchasePaid {
|
|
return false, errors.New("billing: only paid purchases can be converted")
|
|
}
|
|
w, err := b.store.EnsureWallet(ctx, db.OwnerUser, p.UserID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return b.move(ctx, db.LedgerCredit, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID, p.PaymentMethod)
|
|
}
|
|
|
|
// --- reconciliation --------------------------------------------------------
|
|
|
|
// ReconcileResult summarizes one reconciliation pass.
|
|
type ReconcileResult struct {
|
|
Checked int
|
|
Settled int
|
|
Errors int
|
|
}
|
|
|
|
// Reconcile checks unsettled purchases against LNbits: all pending ones,
|
|
// plus those that expired or were cancelled within the given window. It is
|
|
// run with a long window at startup and with a short one while polling.
|
|
func (b *Billing) Reconcile(ctx context.Context, window time.Duration) (ReconcileResult, error) {
|
|
var res ReconcileResult
|
|
if b.ln == nil {
|
|
return res, nil
|
|
}
|
|
list, err := b.store.UnsettledPurchases(ctx, b.nowMilli()-window.Milliseconds(), 1000)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
for _, p := range list {
|
|
if ctx.Err() != nil {
|
|
return res, ctx.Err()
|
|
}
|
|
res.Checked++
|
|
settled, err := b.checkOne(ctx, p)
|
|
if err != nil {
|
|
res.Errors++
|
|
if errors.Is(err, ErrLightningDown) {
|
|
// No point hammering a backend that is down.
|
|
return res, err
|
|
}
|
|
b.log.Error("reconcile purchase", "purchase_id", p.ID, "err", err)
|
|
continue
|
|
}
|
|
if settled {
|
|
res.Settled++
|
|
}
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// Windows used by Run.
|
|
const (
|
|
startupWindow = 7 * 24 * time.Hour
|
|
pollWindow = time.Hour
|
|
)
|
|
|
|
// Run reconciles everything once and then keeps polling until ctx ends.
|
|
// Pending invoices are checked every interval. Invoices that closed
|
|
// recently are checked on every twelfth pass, which is enough to catch a
|
|
// payment that crossed with an expiry.
|
|
func (b *Billing) Run(ctx context.Context) {
|
|
if b.ln == nil {
|
|
return
|
|
}
|
|
if res, err := b.Reconcile(ctx, startupWindow); err != nil {
|
|
b.log.Error("startup reconciliation failed, will keep trying", "err", err)
|
|
} else {
|
|
b.log.Info("startup reconciliation done", "checked", res.Checked, "settled", res.Settled)
|
|
}
|
|
interval := b.cfg.LNbits.PollInterval.D()
|
|
if interval <= 0 {
|
|
interval = 5 * time.Second
|
|
}
|
|
t := time.NewTicker(interval)
|
|
defer t.Stop()
|
|
for tick := 1; ; tick++ {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
window := time.Duration(0)
|
|
if tick%12 == 0 {
|
|
window = pollWindow
|
|
}
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Health checks the payment backend and remembers the outcome.
|
|
func (b *Billing) Health(ctx context.Context) error {
|
|
if b.ln == nil {
|
|
return nil
|
|
}
|
|
err := b.ln.Health(ctx)
|
|
b.setReachable(err == nil)
|
|
return err
|
|
}
|