package billing import ( "context" "errors" "strings" "time" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/ids" ) // Telegram Stars are the second way to pay, next to Lightning, for passes // and credit packs. Their prices are set on their own (StarsPrices), never // converted from sats. A Stars purchase grants exactly what the same // Lightning purchase grants, through the same settlement, so entitlement // does not care how something was paid. // // The flow is Telegram's: the bot sends an invoice in XTR (or makes an // invoice link for the Mini App), Telegram asks the bot to confirm with a // pre-checkout query, takes the Stars, and sends a message with a // successful_payment. Its telegram_payment_charge_id is stored with the // purchase under a unique index, so a repeated event settles nothing twice. // Errors of Stars payments. var ( ErrStarsOff = errors.New("billing: stars payments are off") ErrNotForStars = errors.New("billing: this is not sold for stars") ErrStarsMismatch = errors.New("billing: the payment does not match the invoice") ErrInvoiceClosed = errors.New("billing: the invoice is closed") ErrUnknownCharge = errors.New("billing: unknown payment") ) // StarsPayloadPrefix starts the invoice payload of a Stars purchase. const StarsPayloadPrefix = "dlp:" // starsInvoiceLife is how long a Stars purchase is shown as open. Telegram // invoices do not expire, so a payment that comes later still settles. const starsInvoiceLife = 24 * time.Hour // StarsEnabled reports whether Stars are offered. func (b *Billing) StarsEnabled() bool { return b.cfg.StarsEnabled } // Selling reports whether anything can be bought, by either method. func (b *Billing) Selling() bool { return b.Enabled() || b.StarsEnabled() } // StarsPrice returns the price in Stars of a product, or false when it is // not sold for Stars. func (b *Billing) StarsPrice(product string, amount int64) (int64, bool) { if !b.StarsEnabled() { return 0, false } switch { case passKind(product) != "": return b.cfg.StarsPrice(product, 0) case product == ProductCredits: return b.cfg.StarsPrice(product, amount) } return 0, false } // StarsPayload is the invoice payload of a Stars purchase. func StarsPayload(p *db.Purchase) string { return StarsPayloadPrefix + p.ID } // CreateStarsPurchase records a purchase to be paid in Stars. The caller // sends the invoice. amount_sats keeps the sats value of what is bought: // the credit pack, or the pass's Lightning price, for the books. func (b *Billing) CreateStarsPurchase(ctx context.Context, np NewPurchase) (*db.Purchase, error) { if !b.StarsEnabled() { return nil, ErrStarsOff } stars, ok := b.StarsPrice(np.Product, np.Amount) if !ok { return nil, ErrNotForStars } sats, err := b.Price(np.Product, np.Amount) if err != nil { return nil, err } now := b.nowMilli() id := ids.New() p := &db.Purchase{ ID: id, UserID: np.UserID, WalletID: np.WalletID, Product: np.Product, AmountSats: sats, Status: db.PurchasePending, PaymentHash: "stars:" + id, Lang: np.Lang, RequestID: np.RequestID, Profile: np.Profile, DeliveryID: np.DeliveryID, CreatedAt: now, ExpiresAt: now + starsInvoiceLife.Milliseconds(), PaymentMethod: db.PayStars, StarsAmount: stars, } if err := b.store.InsertPurchase(ctx, p); err != nil { return nil, err } b.log.Info("stars invoice created", "purchase_id", p.ID, "product", p.Product, "stars", stars, "user_id", np.UserID) return p, nil } // starsPurchase finds the purchase an invoice payload names, for its payer. func (b *Billing) starsPurchase(ctx context.Context, payload string, userID int64) (*db.Purchase, error) { id, ok := strings.CutPrefix(payload, StarsPayloadPrefix) if !ok { return nil, ErrUnknownCharge } p, err := b.store.GetPurchase(ctx, id) if errors.Is(err, db.ErrNotFound) { return nil, ErrUnknownCharge } if err != nil { return nil, err } if p.PaymentMethod != db.PayStars || p.UserID != userID { return nil, ErrUnknownCharge } return p, nil } // PreCheckStars decides a pre-checkout query: Telegram is about to take // the Stars and asks whether the order still stands. func (b *Billing) PreCheckStars(ctx context.Context, payload string, userID int64, currency string, total int64) error { p, err := b.starsPurchase(ctx, payload, userID) if err != nil { return err } if currency != "XTR" || total != p.StarsAmount { return ErrStarsMismatch } if p.Status != db.PurchasePending { return ErrInvoiceClosed } return nil } // SettleStars settles a purchase from a successful_payment. The same // payment arriving again changes nothing: settled is then false and the // purchase is returned as it is. func (b *Billing) SettleStars(ctx context.Context, payload, chargeID string, userID int64, currency string, total int64) (bool, *db.Purchase, error) { if chargeID == "" { return false, nil, ErrUnknownCharge } if p, err := b.store.GetPurchaseByCharge(ctx, chargeID); err == nil { return false, p, nil // seen before } p, err := b.starsPurchase(ctx, payload, userID) if err != nil { return false, nil, err } if currency != "XTR" || total != p.StarsAmount { b.log.Error("stars payment does not match its invoice", "purchase_id", p.ID, "currency", currency, "total", total, "want", p.StarsAmount) return false, p, ErrStarsMismatch } settled, paid, err := b.settle(ctx, p.ID, func(tx *db.Store) error { return tx.SetPurchaseCharge(ctx, p.ID, chargeID) }) if err != nil { return false, p, err } if !settled { cur, err := b.store.GetPurchase(ctx, p.ID) return false, cur, err } return true, paid, nil } // UndoStarsPurchase takes back what a refunded Stars purchase granted: // the credits (as far as they are left) or the pass. It is safe to call // more than once; only the first call changes anything. The Stars // themselves are returned by Telegram (refundStarPayment). func (b *Billing) UndoStarsPurchase(ctx context.Context, purchaseID string) (bool, error) { var undone bool err := b.store.InTx(ctx, func(tx *db.Store) error { now := b.nowMilli() won, err := tx.MarkPurchaseRefunded(ctx, purchaseID, now) if err != nil || !won { return err } p, err := tx.GetPurchase(ctx, purchaseID) if err != nil { return err } switch { case p.Product == ProductCredits: w, err := tx.GetWallet(ctx, p.WalletID) if err != nil { return err } take := min(w.Balance, p.AmountSats) if take > 0 { if _, err := tx.AddLedger(ctx, &db.LedgerEntry{ WalletID: p.WalletID, Kind: db.LedgerDebit, Amount: take, Reason: "stars_refund", Ref: p.ID, DedupeKey: "stars-refund:" + p.ID, CreatedAt: now, PaymentMethod: db.PayStars, }); err != nil { return err } } case passKind(p.Product) != "": if _, err := tx.RemovePassesFrom(ctx, p.WalletID, p.ID); err != nil { return err } } undone = true return nil }) if err == nil && undone { b.log.Info("stars purchase refunded", "purchase_id", purchaseID) } return undone, err }