Phase 4: Telegram Stars payments
- 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>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f7ceadc462
commit
2b5625e9d4
+30
-13
@@ -196,26 +196,26 @@ func (b *Billing) State(ctx context.Context, ownerType string, ownerID int64) (e
|
||||
|
||||
// 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)
|
||||
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)
|
||||
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)
|
||||
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) (bool, error) {
|
||||
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(),
|
||||
DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(), PaymentMethod: method,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -390,7 +390,9 @@ func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (*
|
||||
if p.UserID != userID {
|
||||
return nil, ErrNotOwner
|
||||
}
|
||||
if p.Status != db.PurchasePaid {
|
||||
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
|
||||
}
|
||||
@@ -400,7 +402,7 @@ func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (*
|
||||
|
||||
// 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 {
|
||||
if p.Status == db.PurchasePaid || p.PaymentMethod == db.PayStars {
|
||||
return false, nil
|
||||
}
|
||||
if b.ln == nil {
|
||||
@@ -442,6 +444,13 @@ func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, e
|
||||
// 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
|
||||
@@ -452,6 +461,11 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
|
||||
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
|
||||
}
|
||||
@@ -460,6 +474,7 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
|
||||
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
|
||||
}
|
||||
@@ -483,18 +498,18 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, db.ErrDuplicate) {
|
||||
return false, nil // another connection settled it first
|
||||
return false, nil, nil // another connection settled it first
|
||||
}
|
||||
if err != nil || !settled {
|
||||
return false, err
|
||||
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,
|
||||
"user_id", p.UserID, "wallet_id", p.WalletID)
|
||||
"stars", p.StarsAmount, "method", p.PaymentMethod, "user_id", p.UserID, "wallet_id", p.WalletID)
|
||||
b.emit(EventPaid, p)
|
||||
return true, nil
|
||||
return true, p, nil
|
||||
}
|
||||
|
||||
// rewardReferrer pays the inviter of a user who settled their first
|
||||
@@ -544,7 +559,9 @@ func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purcha
|
||||
|
||||
// countsForReferral reports whether a purchase was paid in a way our
|
||||
// referral program rewards: Lightning.
|
||||
func countsForReferral(p *db.Purchase) bool { return true }
|
||||
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) {
|
||||
@@ -642,7 +659,7 @@ func (b *Billing) ConvertToCredits(ctx context.Context, p *db.Purchase) (bool, e
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return b.Credit(ctx, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID)
|
||||
return b.move(ctx, db.LedgerCredit, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID, p.PaymentMethod)
|
||||
}
|
||||
|
||||
// --- reconciliation --------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package billing_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/billing"
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
)
|
||||
|
||||
const bob = int64(43)
|
||||
|
||||
func starsRig(t *testing.T) *rig {
|
||||
t.Helper()
|
||||
r := newRig(t)
|
||||
r.cfg.StarsEnabled = true
|
||||
r.b = r.newBilling()
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *rig) buyStars(user int64, product string, amount int64) *db.Purchase {
|
||||
r.t.Helper()
|
||||
p, err := r.b.CreateStarsPurchase(context.Background(), billing.NewPurchase{
|
||||
UserID: user, WalletID: r.wallet(user).ID, Product: product, Amount: amount, Lang: "en",
|
||||
})
|
||||
if err != nil {
|
||||
r.t.Fatalf("CreateStarsPurchase: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func TestStarsPricesAreTheirOwn(t *testing.T) {
|
||||
r := starsRig(t)
|
||||
ctx := context.Background()
|
||||
p := r.buyStars(alice, billing.ProductCredits, 5000)
|
||||
if p.PaymentMethod != db.PayStars || p.StarsAmount != 330 || p.AmountSats != 5000 || p.Bolt11 != "" {
|
||||
t.Fatalf("purchase = %+v", p)
|
||||
}
|
||||
// Only passes and credit packs with a configured price are sold.
|
||||
for _, c := range []struct {
|
||||
product string
|
||||
amount int64
|
||||
}{{billing.ProductOneOff, 1000}, {billing.ProductDonation, 500}, {billing.ProductCredits, 1234}, {billing.ProductSkipQueue, 0}} {
|
||||
_, err := r.b.CreateStarsPurchase(ctx, billing.NewPurchase{UserID: alice, WalletID: r.wallet(alice).ID, Product: c.product, Amount: c.amount})
|
||||
if !errors.Is(err, billing.ErrNotForStars) {
|
||||
t.Errorf("%s %d: %v, want ErrNotForStars", c.product, c.amount, err)
|
||||
}
|
||||
}
|
||||
// Off means off.
|
||||
r.cfg.StarsEnabled = false
|
||||
r.b = r.newBilling()
|
||||
if _, err := r.b.CreateStarsPurchase(ctx, billing.NewPurchase{UserID: alice, WalletID: r.wallet(alice).ID, Product: billing.ProductPassDay}); !errors.Is(err, billing.ErrStarsOff) {
|
||||
t.Fatalf("stars off: %v", err)
|
||||
}
|
||||
if creates, statuses := r.ln.Calls(); creates != 0 || statuses != 0 {
|
||||
t.Fatalf("a Stars purchase talked to LNbits: %d creates, %d statuses", creates, statuses)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStarsPreCheckout(t *testing.T) {
|
||||
r := starsRig(t)
|
||||
ctx := context.Background()
|
||||
p := r.buyStars(alice, billing.ProductPassDay, 0)
|
||||
payload := billing.StarsPayload(p)
|
||||
cases := []struct {
|
||||
name string
|
||||
payload string
|
||||
user int64
|
||||
currency string
|
||||
total int64
|
||||
want error
|
||||
}{
|
||||
{"matches", payload, alice, "XTR", 50, nil},
|
||||
{"other amount", payload, alice, "XTR", 49, billing.ErrStarsMismatch},
|
||||
{"other currency", payload, alice, "USD", 50, billing.ErrStarsMismatch},
|
||||
{"other payer", payload, bob, "XTR", 50, billing.ErrUnknownCharge},
|
||||
{"unknown payload", "dlp:nope", alice, "XTR", 50, billing.ErrUnknownCharge},
|
||||
{"foreign payload", "something else", alice, "XTR", 50, billing.ErrUnknownCharge},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if err := r.b.PreCheckStars(ctx, c.payload, c.user, c.currency, c.total); !errors.Is(err, c.want) {
|
||||
t.Errorf("%s: %v, want %v", c.name, err, c.want)
|
||||
}
|
||||
}
|
||||
// A cancelled invoice is not paid any more.
|
||||
if _, err := r.b.Cancel(ctx, p.ID, alice); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.b.PreCheckStars(ctx, payload, alice, "XTR", 50); !errors.Is(err, billing.ErrInvoiceClosed) {
|
||||
t.Fatalf("cancelled: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStarsPaymentGrantsTheSameAsLightningOnce(t *testing.T) {
|
||||
r := starsRig(t)
|
||||
ctx := context.Background()
|
||||
// The same pass, once over Lightning (bob) and once in Stars (alice).
|
||||
_ = r.ln.Pay(r.buy(bob, billing.ProductPassWeek, 0).PaymentHash)
|
||||
p := r.buyStars(alice, billing.ProductPassWeek, 0)
|
||||
settled, paid, err := r.b.SettleStars(ctx, billing.StarsPayload(p), "charge-1", alice, "XTR", 200)
|
||||
if err != nil || !settled || paid.Status != db.PurchasePaid || paid.ChargeID != "charge-1" {
|
||||
t.Fatalf("SettleStars = %v, %+v, %v", settled, paid, err)
|
||||
}
|
||||
stA, _ := r.b.State(ctx, db.OwnerUser, alice)
|
||||
stB, _ := r.b.State(ctx, db.OwnerUser, bob)
|
||||
if stA.PassUntil == 0 || stA.PassUntil != stB.PassUntil {
|
||||
t.Fatalf("pass until: stars %d, lightning %d", stA.PassUntil, stB.PassUntil)
|
||||
}
|
||||
// The same payment event again, and again with the poll: nothing new.
|
||||
for i := 0; i < 3; i++ {
|
||||
again, cur, err := r.b.SettleStars(ctx, billing.StarsPayload(p), "charge-1", alice, "XTR", 200)
|
||||
if err != nil || again || cur.ID != p.ID {
|
||||
t.Fatalf("repeat %d: %v %+v %v", i, again, cur, err)
|
||||
}
|
||||
}
|
||||
if n := r.count(billing.EventPaid); n != 2 {
|
||||
t.Fatalf("%d paid events, want 2 (one per purchase)", n)
|
||||
}
|
||||
if _, err := r.b.Reconcile(ctx, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ := r.b.State(ctx, db.OwnerUser, alice); st.PassUntil != stA.PassUntil {
|
||||
t.Fatal("the pass was extended twice")
|
||||
}
|
||||
|
||||
// Credits: the pack's sats arrive in the wallet, marked as paid in Stars.
|
||||
c := r.buyStars(alice, billing.ProductCredits, 1000)
|
||||
if _, _, err := r.b.SettleStars(ctx, billing.StarsPayload(c), "charge-2", alice, "XTR", 70); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := r.balance(alice); got != 1000 {
|
||||
t.Fatalf("balance = %d", got)
|
||||
}
|
||||
if l := r.ledger(alice); len(l) == 0 || l[0].PaymentMethod != db.PayStars {
|
||||
t.Fatalf("ledger = %+v", l)
|
||||
}
|
||||
// A payment that does not match its invoice is not settled.
|
||||
m := r.buyStars(alice, billing.ProductCredits, 5000)
|
||||
if _, _, err := r.b.SettleStars(ctx, billing.StarsPayload(m), "charge-3", alice, "XTR", 1); !errors.Is(err, billing.ErrStarsMismatch) {
|
||||
t.Fatalf("mismatch: %v", err)
|
||||
}
|
||||
r.booksBalance()
|
||||
}
|
||||
|
||||
func TestStarsRefundUndoesThePurchase(t *testing.T) {
|
||||
r := starsRig(t)
|
||||
ctx := context.Background()
|
||||
c := r.buyStars(alice, billing.ProductCredits, 1000)
|
||||
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(c), "c1", alice, "XTR", 70)
|
||||
pass := r.buyStars(alice, billing.ProductPassDay, 0)
|
||||
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(pass), "c2", alice, "XTR", 50)
|
||||
week := r.buyStars(alice, billing.ProductPassWeek, 0)
|
||||
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(week), "c3", alice, "XTR", 200)
|
||||
before, _ := r.b.State(ctx, db.OwnerUser, alice)
|
||||
|
||||
// The day pass goes; the week pass stacked after it moves up a day.
|
||||
if ok, err := r.b.UndoStarsPurchase(ctx, pass.ID); err != nil || !ok {
|
||||
t.Fatalf("undo pass: %v %v", ok, err)
|
||||
}
|
||||
after, _ := r.b.State(ctx, db.OwnerUser, alice)
|
||||
if got := before.PassUntil - after.PassUntil; got != (24 * time.Hour).Milliseconds() {
|
||||
t.Fatalf("pass shortened by %d ms, want one day", got)
|
||||
}
|
||||
// Credits are taken back as far as they are left.
|
||||
if ok, _ := r.b.UndoStarsPurchase(ctx, c.ID); !ok || r.balance(alice) != 0 {
|
||||
t.Fatalf("balance after refund = %d", r.balance(alice))
|
||||
}
|
||||
// Once only, and never for a Lightning purchase.
|
||||
if ok, _ := r.b.UndoStarsPurchase(ctx, c.ID); ok {
|
||||
t.Fatal("refunded twice")
|
||||
}
|
||||
ln := r.buy(bob, billing.ProductCredits, 1000)
|
||||
_ = r.ln.Pay(ln.PaymentHash)
|
||||
if ok, _ := r.b.UndoStarsPurchase(ctx, ln.ID); ok || r.balance(bob) != 1000 {
|
||||
t.Fatal("a Lightning purchase was undone as a Stars refund")
|
||||
}
|
||||
if p := r.purchase(pass.ID); p.Status != db.PurchaseRefunded || p.RefundedAt == 0 {
|
||||
t.Fatalf("purchase = %+v", p)
|
||||
}
|
||||
r.booksBalance()
|
||||
}
|
||||
|
||||
func TestStarsPurchasesEarnNoSatsReferral(t *testing.T) {
|
||||
r := starsRig(t)
|
||||
ctx := context.Background()
|
||||
const inviter, invited = int64(700), int64(701)
|
||||
for _, id := range []int64{inviter, invited} {
|
||||
if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := r.store.SetReferrer(ctx, invited, inviter); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Telegram's affiliate program covers Stars; our sats reward does not.
|
||||
p := r.buyStars(invited, billing.ProductPassDay, 0)
|
||||
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(p), "c1", invited, "XTR", 50)
|
||||
if r.balance(inviter) != 0 {
|
||||
t.Fatal("a Stars purchase paid a sats referral reward")
|
||||
}
|
||||
// The first Lightning purchase after it does.
|
||||
_ = r.ln.Pay(r.buy(invited, billing.ProductCredits, 1000).PaymentHash)
|
||||
if r.balance(inviter) != 200 {
|
||||
t.Fatalf("inviter balance = %d, want 200", r.balance(inviter))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user