Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/patron/v0"
gno = "0.9"

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 755144
  max_deposit = "16000000ugnot"

patron.gno

// Package patron is the engine behind recurring support for a builder: a plan
// somebody subscribes to, period after period, paid in ugnot on chain.
//
// # There is no cron on chain, so a renewal is a pull and not a push
//
// Nothing here can charge anybody. The supporter sends another payment and
// their paid-through height moves forward; there is no scheduler, no keeper,
// and no standing authority over anybody's balance. There is no way to write
// one either, because a native coin cannot be pulled at all: a banker may only
// spend its own realm's address, so the inbound path is always the holder
// signing. A reader arriving from web2 expects the opposite, and that is the
// one expectation to unlearn before reading the rest of this package.
//
// # What this adds over a tip jar
//
// A tip jar is one payment and then nothing, and the one-shot version is
// already live at gno.land/r/moul/x/daily/tipjar. The recurrence is the only
// reason this exists: a plan carries a price per period and a period measured
// in BLOCKS, a supporter buys whole periods, and anybody can ask at any height
// whether a given address is still active. It is the one piece of the x/social
// family that produces a recurring write rather than a one-off.
//
// # The model
//
//	Registry  every plan, plus the credit ledger money leaves through
//	Plan      a creator, a title, a description, a price, a period, open or not
//	Payment   what one Subscribe call bought: periods, spent, change, through
//
// # Renewing early never loses time already paid for
//
// [Registry.Subscribe] extends from whichever is LATER, now or the supporter's
// current paid-through height. Renewing two blocks before a lapse adds a whole
// period on top of what is left. Renewing after a lapse starts from now,
// because the gap was never paid for and nothing backdates it.
//
// # The change is credited back, never kept
//
// A payment buys floor(sent / price) whole periods, and the remainder under
// one period is credited to the SUPPORTER's own withdrawable balance. Keeping
// it would be a fee nobody agreed to, and a silent fee is the thing a
// subscription realm must not have. The supporter takes it back through the
// same [Registry.Withdraw] a creator uses.
//
// # Earnings are credited at the moment of payment, not streamed
//
// The creator can withdraw the whole price the instant it is paid. A supporter
// who stops being active is therefore NOT refunded, and no part of a paid
// period is ever returned. That is a real limitation and it is v0 on purpose:
// escrowed streaming, where the creator claims only what has elapsed and the
// supporter can cancel and reclaim the rest, needs a claim schedule and a
// refund path, which is a bigger realm than this one. It is the v1, and it is
// not a line that can be bolted onto this one.
//
// # Money leaves by pull, never by a push loop
//
// Nothing here moves coins. [Registry.Subscribe] credits a
// gno.land/p/moul/x/daily/pullpayment ledger, and [Registry.Withdraw] zeroes a
// credit and reports what was owed so the holding realm can transfer after
// that call, with the balance already gone when control leaves. A realm that
// looped over payees instead would fail entirely on one unpayable address and
// hand a griefer a cheap denial of service.
//
// # A title and a description are attacker-controlled markdown
//
// Both are free text. [ValidTitle] and [ValidDescription] bound them and
// refuse control characters, which is a different protection from escaping and
// not a substitute for it: a realm that renders either one escapes it with
// ui.Inline in prose or ui.Cell in a table cell.
package patron

import (
	"chain/markdown"
	"errors"
	"strings"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/pullpayment/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/xmath/v1"
)

const (
	// MaxTitleLen and MaxDescriptionLen bound the two free-text fields. Long
	// enough to say what the plan is, short enough that opening one cannot
	// lock an unbounded storage deposit somebody else is paying for.
	MaxTitleLen       = 80
	MaxDescriptionLen = 500

	// MinPeriodBlocks and MaxPeriodBlocks bound a period both ways. A period
	// of zero blocks is not a subscription, it is a division by zero wearing
	// a price tag. The ceiling is about a year at the five second blocks the
	// test chain runs, past which "recurring" stops meaning anything and the
	// plan is a one-off with extra steps.
	MinPeriodBlocks = int64(10)
	MaxPeriodBlocks = int64(6307200)

	// MinPricePerPeriod is one ugnot, because a free plan is a tip jar
	// (gno.land/r/moul/x/daily/tipjar) and not a subscription: at a price of
	// zero there is nothing to buy a period with and every address would be
	// active forever.
	MinPricePerPeriod = int64(1)

	// MaxPeriodsPerPayment bounds what one payment may buy. It keeps
	// periods * PeriodBlocks inside an int64 by construction rather than by
	// hope, and it stops a single send from parking a paid-through height so
	// far ahead that no later arithmetic on it means anything.
	MaxPeriodsPerPayment = int64(10000)
)

// The errors a caller can get back. A p/ package returns them and the realm
// decides to abort.
var (
	ErrBadTitle          = errors.New("patron: title is empty, too long, or has control characters")
	ErrBadDescription    = errors.New("patron: description is too long or has control characters")
	ErrBadPrice          = errors.New("patron: a plan needs a price of at least one ugnot per period")
	ErrBadPeriod         = errors.New("patron: period out of range")
	ErrNoPlan            = errors.New("patron: no such plan")
	ErrPlanClosed        = errors.New("patron: this plan is closed to new subscriptions")
	ErrNotCreator        = errors.New("patron: only the plan's creator can do that")
	ErrAlreadyOpen       = errors.New("patron: the plan is already open")
	ErrAlreadyClosed     = errors.New("patron: the plan is already closed")
	ErrShortOfOnePeriod  = errors.New("patron: the payment does not cover one whole period")
	ErrTooManyPeriods    = errors.New("patron: one payment cannot buy that many periods")
	ErrNothingToWithdraw = errors.New("patron: nothing to withdraw")
)

// Plan is one creator's recurring support plan.
type Plan struct {
	Creator     address
	Title       string
	Description string

	// PricePerPeriod is what one period costs, in ugnot.
	PricePerPeriod int64

	// PeriodBlocks is how long a period lasts, in blocks. Blocks and not
	// seconds: height is the clock consensus agrees on, and a block timestamp
	// is set by proposers and is not something to build a billing cliff out
	// of at second resolution.
	PeriodBlocks int64

	// Open reports whether the plan takes NEW payments. Closing it never
	// touches a subscription already paid for, which runs to its own
	// paid-through height.
	Open bool

	// Received is the lifetime ugnot this plan credited to its creator.
	Received int64

	// paidThrough is the first height at which a supporter is no longer
	// active. A supporter is active while now < paidThrough, so a period
	// bought at height h ends at h+PeriodBlocks and the holder is inactive
	// at exactly that height.
	paidThrough map[string]int64

	// supporters is every address that has ever paid, in first-payment
	// order. It exists so a listing is deterministic without iterating a map
	// as if insertion order were a sort.
	supporters []address
}

// PaidThrough is the height who stops being active at, or zero if they never
// paid.
func (p *Plan) PaidThrough(who address) int64 {
	if p == nil {
		return 0
	}
	return p.paidThrough[who.String()]
}

// IsActive reports whether who is paid up at height now.
//
// The comparison is strict: a supporter paid through height h is active at
// h-1 and not at h. One rule, applied at both edges, so a period never
// overlaps the next one by a block.
func (p *Plan) IsActive(who address, now int64) bool {
	return p.PaidThrough(who) > now
}

// SupporterCount is how many distinct addresses have ever paid, active or not.
func (p *Plan) SupporterCount() int {
	if p == nil {
		return 0
	}
	return len(p.supporters)
}

// Supporters is every address that has ever paid, in first-payment order.
//
// It returns a copy. Handing out the stored slice would be a live mutation
// handle on realm state, which is the cheapest way for a reader to become a
// writer.
func (p *Plan) Supporters() []address {
	if p == nil {
		return nil
	}
	out := make([]address, len(p.supporters))
	copy(out, p.supporters)
	return out
}

// ActiveCount is how many supporters are paid up at height now.
func (p *Plan) ActiveCount(now int64) int {
	if p == nil {
		return 0
	}
	n := 0
	for _, who := range p.supporters {
		if p.IsActive(who, now) {
			n++
		}
	}
	return n
}

// Payment is what one [Registry.Subscribe] call bought.
type Payment struct {
	// Periods is how many whole periods the payment covered.
	Periods int64

	// Spent is the ugnot those periods cost, credited to the creator.
	Spent int64

	// Change is the remainder under one period, credited back to the
	// supporter rather than kept.
	Change int64

	// PaidThrough is the supporter's new paid-through height.
	PaidThrough int64

	// NewSupporter reports whether this address had never paid this plan
	// before, which is the signal a realm wants for an event or a counter.
	NewSupporter bool
}

// Registry holds every plan and the credit ledger money leaves through.
type Registry struct {
	plans  *store.Store
	ledger *pullpayment.Ledger

	// earned is lifetime ugnot credited per creator, which survives a
	// withdrawal. The ledger only knows what is owed RIGHT NOW, and a page
	// showing a creator zero the moment they cash out would be telling the
	// truth about the wrong question.
	earned map[string]int64
}

// NewRegistry returns an empty registry.
func NewRegistry() *Registry {
	return &Registry{
		plans:  store.Named("plan"),
		ledger: pullpayment.New(),
		earned: map[string]int64{},
	}
}

// Open creates a plan and returns its id. Anyone may open one.
func (r *Registry) Open(creator address, title, description string, pricePerPeriod, periodBlocks int64) (store.ID, error) {
	if !ValidTitle(title) {
		return 0, ErrBadTitle
	}
	if !ValidDescription(description) {
		return 0, ErrBadDescription
	}
	if pricePerPeriod < MinPricePerPeriod {
		return 0, ErrBadPrice
	}
	if periodBlocks < MinPeriodBlocks || periodBlocks > MaxPeriodBlocks {
		return 0, ErrBadPeriod
	}
	return r.plans.Add(&Plan{
		Creator:        creator,
		Title:          title,
		Description:    description,
		PricePerPeriod: pricePerPeriod,
		PeriodBlocks:   periodBlocks,
		Open:           true,
		paidThrough:    map[string]int64{},
	}), nil
}

// Subscribe buys whole periods on a plan with sent ugnot, at height now.
//
// It refuses anything short of one period, buys floor(sent / price) of them,
// and credits the remainder back to the supporter. The extension starts from
// whichever is LATER, now or the supporter's current paid-through height, so
// renewing early never discards time already paid for and renewing after a
// lapse never backdates the gap.
//
// The creator is credited at the moment of payment, not as the periods
// elapse. See the package doc for why that is v0 and what v1 would have to
// carry instead.
func (r *Registry) Subscribe(id store.ID, who address, sent, now int64) (Payment, error) {
	p, ok := r.Get(id)
	if !ok {
		return Payment{}, ErrNoPlan
	}
	if !p.Open {
		return Payment{}, ErrPlanClosed
	}
	if sent < p.PricePerPeriod {
		return Payment{}, ErrShortOfOnePeriod
	}

	// The one rounding decision in this function: periods is floor, so a
	// supporter is never sold a period they did not fully fund, and the
	// remainder is handed back below rather than kept. Neither side keeps a
	// fraction of a period.
	periods := sent / p.PricePerPeriod
	if periods > MaxPeriodsPerPayment {
		return Payment{}, ErrTooManyPeriods
	}
	spent := sent - sent%p.PricePerPeriod
	change := sent - spent

	// spent is an exact whole number of periods, so this division leaves no
	// remainder and there is no second rounding direction to choose. MulDiv
	// is here for the intermediate: spent * PeriodBlocks overflows an int64
	// for a plan priced in whole GNOT with a period measured in months, and
	// the naive product wraps to a plausible-looking height rather than to an
	// obvious one. MulDivUp would be identical on an exact division; MulDiv
	// says plainly that nothing is being rounded up.
	added := xmath.MulDiv(spent, p.PeriodBlocks, p.PricePerPeriod)

	from := now
	if pt := p.PaidThrough(who); pt > from {
		from = pt
	}
	through := from + added

	key := who.String()

	// Both credits happen before the plan is touched, and both can fail: the
	// ledger is bounded and guards its own overflow. A realm calling this
	// aborts on the error, which reverts everything written in the same
	// frame, so a half-applied subscription is not reachable from a crossing
	// call. The ordering is what makes that true for every other caller too.
	if err := r.ledger.Credit(p.Creator.String(), spent); err != nil {
		return Payment{}, err
	}
	if change > 0 {
		if err := r.ledger.Credit(key, change); err != nil {
			return Payment{}, err
		}
	}
	r.earned[p.Creator.String()] += spent

	_, seen := p.paidThrough[key]
	if !seen {
		p.supporters = append(p.supporters, who)
	}
	p.paidThrough[key] = through
	p.Received += spent

	return Payment{
		Periods:      periods,
		Spent:        spent,
		Change:       change,
		PaidThrough:  through,
		NewSupporter: !seen,
	}, nil
}

// Close stops a plan taking new subscriptions. Creator only.
//
// It does not touch anything already paid for: existing supporters run to
// their own paid-through height, which is the only behaviour that does not
// turn closing a plan into taking money back.
func (r *Registry) Close(id store.ID, who address) error {
	p, err := r.ownPlan(id, who)
	if err != nil {
		return err
	}
	if !p.Open {
		return ErrAlreadyClosed
	}
	p.Open = false
	return nil
}

// Reopen lets a closed plan take subscriptions again. Creator only.
func (r *Registry) Reopen(id store.ID, who address) error {
	p, err := r.ownPlan(id, who)
	if err != nil {
		return err
	}
	if p.Open {
		return ErrAlreadyOpen
	}
	p.Open = true
	return nil
}

// ownPlan is the shared lookup plus authority check, so Close and Reopen
// cannot drift apart on who is allowed to call them.
func (r *Registry) ownPlan(id store.ID, who address) (*Plan, error) {
	p, ok := r.Get(id)
	if !ok {
		return nil, ErrNoPlan
	}
	if p.Creator != who {
		return nil, ErrNotCreator
	}
	return p, nil
}

// Withdraw zeroes who's credit and reports what they were owed.
//
// It moves no coins. The holding realm transfers the returned amount AFTER
// this call, which is the whole point of the pattern: the credit is already
// gone from the ledger when control passes to the payee, so a reentrant call
// finds nothing and gets [ErrNothingToWithdraw].
func (r *Registry) Withdraw(who address) (int64, error) {
	amount, err := r.ledger.Withdraw(who.String())
	if err != nil {
		return 0, ErrNothingToWithdraw
	}
	return amount, nil
}

// CreditOf is what addr can withdraw right now: earnings as a creator, change
// as a supporter, or both.
func (r *Registry) CreditOf(addr address) int64 { return r.ledger.Balance(addr.String()) }

// EarnedBy is the lifetime ugnot credited to creator across every plan,
// whether or not it has been withdrawn.
func (r *Registry) EarnedBy(creator address) int64 { return r.earned[creator.String()] }

// TotalOwed is everything the holding realm must keep in reserve.
func (r *Registry) TotalOwed() int64 { return r.ledger.TotalOwed() }

// Get returns a plan by id.
func (r *Registry) Get(id store.ID) (*Plan, bool) {
	v, ok := r.plans.Get(id)
	if !ok {
		return nil, false
	}
	return v.(*Plan), true
}

// Count is how many plans exist.
func (r *Registry) Count() int { return r.plans.Len() }

// Listing is one row of [Registry.List]: the plan and the id a link needs.
type Listing struct {
	ID   store.ID
	Plan *Plan
}

// List returns one page of plans, newest first.
func (r *Registry) List(page, size int) []Listing {
	var out []Listing
	for _, e := range r.plans.PageReverse(page, size) {
		out = append(out, Listing{ID: e.ID, Plan: e.Value.(*Plan)})
	}
	return out
}

// Pages is how many pages of the given size the registry holds.
func (r *Registry) Pages(size int) int { return r.plans.Pages(size) }

// ValidTitle reports whether title can be stored: non-empty after the
// render's own stripping and trimming,
// within [MaxTitleLen], and free of control characters including newlines.
//
// A title is one line by construction, so a newline in one is refused rather
// than stripped: silently rewriting what somebody typed is worse than telling
// them it was refused.
func ValidTitle(title string) bool {
	if len(title) > MaxTitleLen || strings.TrimSpace(markdown.StripBidiAndZeroWidth(title)) == "" {
		return false
	}
	for i := 0; i < len(title); i++ {
		if c := title[i]; c < 0x20 || c == 0x7f {
			return false
		}
	}
	return true
}

// ValidDescription reports whether description can be stored: within
// [MaxDescriptionLen] and free of control characters other than newline and
// tab. Empty is allowed, because a plan whose title says it all should not
// have to invent prose.
func ValidDescription(description string) bool {
	if len(description) > MaxDescriptionLen {
		return false
	}
	for i := 0; i < len(description); i++ {
		c := description[i]
		if c < 0x20 && c != '\n' && c != '\t' || c == 0x7f {
			return false
		}
	}
	return true
}

// PlanURL is the gnoweb path of one plan on the hosting realm.
func PlanURL(realmPath string, id store.ID) string {
	return RealmURL(realmPath) + ":plan/" + id.String()
}

// RealmURL is the gnoweb path of a realm given as a package path.
//
// The chain domain is the first element of a package path and a gnoweb path is
// the rest of it, so this is a prefix strip and not a hostname this package
// has to know.
func RealmURL(realmPath string) string {
	if i := strings.Index(realmPath, "/"); i >= 0 {
		return realmPath[i:]
	}
	return "/" + realmPath
}

patron_test.gno

package patron

import (
	"strings"
	"testing"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	carol = testutils.TestAddress("carol")
)

// plan opens one plan with the given price and period and returns its id,
// failing the test rather than returning an error nobody reads.
func plan(t *testing.T, r *Registry, price, period int64) store.ID {
	t.Helper()
	id, err := r.Open(alice, "a plan", "every period, forever", price, period)
	urequire.NoError(t, err)
	return id
}

// planOf reads a plan back, failing the test when it is not there.
func planOf(t *testing.T, r *Registry, id store.ID) *Plan {
	t.Helper()
	p, ok := r.Get(id)
	urequire.True(t, ok, "plan #"+id.String()+" exists")
	return p
}

func TestValidTitle(t *testing.T) {
	tests := []struct {
		name  string
		title string
		want  bool
	}{
		{"plain", "monthly support", true},
		{"markdown is allowed and escaped later", "[x](y) | z", true},
		{"at the limit", strings.Repeat("x", MaxTitleLen), true},
		{"empty", "", false},
		{"blank", "   ", false},
		{"too long", strings.Repeat("x", MaxTitleLen+1), false},
		{"a title is one line", "two\nlines", false},
		{"tab is a control character here", "a\tb", false},
		{"delete character", "a\x7fb", false},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, ValidTitle(tt.title), tt.name)
	}
}

func TestValidDescription(t *testing.T) {
	tests := []struct {
		name string
		desc string
		want bool
	}{
		{"empty is fine, the title may say it all", "", true},
		{"newlines and tabs are content", "a\nb\tc", true},
		{"at the limit", strings.Repeat("x", MaxDescriptionLen), true},
		{"too long", strings.Repeat("x", MaxDescriptionLen+1), false},
		{"control character", "a\x01b", false},
		{"delete character", "a\x7fb", false},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, ValidDescription(tt.desc), tt.name)
	}
}

func TestOpenRejectsWhatItCannotStore(t *testing.T) {
	tests := []struct {
		name   string
		title  string
		desc   string
		price  int64
		period int64
		want   error
	}{
		{"no title", "", "d", 100, 100, ErrBadTitle},
		{"description too long", "t", strings.Repeat("x", MaxDescriptionLen+1), 100, 100, ErrBadDescription},
		{"a free plan is a tip jar", "t", "d", 0, 100, ErrBadPrice},
		{"a negative price", "t", "d", -1, 100, ErrBadPrice},
		{"no period at all", "t", "d", 100, 0, ErrBadPeriod},
		{"under the floor", "t", "d", 100, MinPeriodBlocks - 1, ErrBadPeriod},
		{"over the ceiling", "t", "d", 100, MaxPeriodBlocks + 1, ErrBadPeriod},
	}
	r := NewRegistry()
	for _, tt := range tests {
		_, err := r.Open(alice, tt.title, tt.desc, tt.price, tt.period)
		uassert.ErrorIs(t, err, tt.want, tt.name)
	}
	uassert.Equal(t, 0, r.Count(), "nothing refused was stored")

	// The edges themselves are accepted.
	_, err := r.Open(alice, "t", "", MinPricePerPeriod, MinPeriodBlocks)
	uassert.NoError(t, err)
	_, err = r.Open(alice, "t", "", MinPricePerPeriod, MaxPeriodBlocks)
	uassert.NoError(t, err)
	uassert.Equal(t, 2, r.Count())
}

func TestOnePeriodBuysExactlyOnePeriod(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	pay, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)

	uassert.Equal(t, int64(1), pay.Periods)
	uassert.Equal(t, int64(1000), pay.Spent)
	uassert.Equal(t, int64(0), pay.Change)
	uassert.Equal(t, int64(600), pay.PaidThrough, "500 + one period of 100 blocks")
	uassert.True(t, pay.NewSupporter)

	uassert.Equal(t, int64(1000), r.CreditOf(alice), "the creator is credited at payment time")
	uassert.Equal(t, int64(1000), r.EarnedBy(alice))
	uassert.Equal(t, int64(0), r.CreditOf(bob), "an exact payment leaves no change")
	uassert.Equal(t, int64(1000), r.TotalOwed())
}

func TestThreePeriodsAtOnce(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	pay, err := r.Subscribe(id, bob, 3000, 500)
	urequire.NoError(t, err)

	uassert.Equal(t, int64(3), pay.Periods)
	uassert.Equal(t, int64(3000), pay.Spent)
	uassert.Equal(t, int64(0), pay.Change)
	uassert.Equal(t, int64(800), pay.PaidThrough, "three periods of 100 blocks from 500")
}

// Renewing before the current period ends adds a whole period on top of what
// is left, rather than restarting the clock and discarding it.
func TestRenewingEarlyExtendsFromPaidThrough(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	first, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)
	urequire.Equal(t, int64(600), first.PaidThrough)

	// Two blocks before the lapse, with 98 blocks still paid for.
	second, err := r.Subscribe(id, bob, 1000, 502)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(700), second.PaidThrough, "600 + 100, not 502 + 100")
	uassert.False(t, second.NewSupporter, "bob was already a supporter")
	uassert.Equal(t, 1, planOf(t, r, id).SupporterCount(), "renewing is not a second supporter")
}

// Renewing after a lapse starts from now: the gap was never paid for and
// nothing backdates it.
func TestRenewingAfterLapseStartsFromNow(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	_, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)

	// 900 is long past the 600 the first period ran to.
	second, err := r.Subscribe(id, bob, 1000, 900)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(1000), second.PaidThrough, "900 + 100, the gap is not backdated")
}

// Paying exactly at the paid-through height is the boundary between the two
// rules above, and it resolves the same way either way: 600 is not later than
// 600, so the extension runs from 600.
func TestRenewingAtTheBoundary(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	_, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)
	second, err := r.Subscribe(id, bob, 1000, 600)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(700), second.PaidThrough)
}

func TestAPaymentShortOfOnePeriodIsRefused(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	for _, sent := range []int64{0, 1, 999} {
		_, err := r.Subscribe(id, bob, sent, 500)
		uassert.ErrorIs(t, err, ErrShortOfOnePeriod)
	}
	uassert.Equal(t, int64(0), r.CreditOf(alice), "a refused payment credits nobody")
	uassert.Equal(t, int64(0), planOf(t, r, id).PaidThrough(bob))
	uassert.Equal(t, 0, planOf(t, r, id).SupporterCount())
}

// The remainder under one period is the supporter's, not the realm's: keeping
// it would be a fee nobody agreed to.
func TestChangeIsCreditedBackAndIsWithdrawable(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	pay, err := r.Subscribe(id, bob, 2500, 500)
	urequire.NoError(t, err)

	uassert.Equal(t, int64(2), pay.Periods)
	uassert.Equal(t, int64(2000), pay.Spent)
	uassert.Equal(t, int64(500), pay.Change)
	uassert.Equal(t, int64(700), pay.PaidThrough)

	uassert.Equal(t, int64(500), r.CreditOf(bob), "the change is the supporter's")
	uassert.Equal(t, int64(2000), r.CreditOf(alice))
	uassert.Equal(t, int64(2500), r.TotalOwed(), "every ugnot that came in is owed to somebody")
	uassert.Equal(t, int64(0), r.EarnedBy(bob), "change is not earnings")

	got, err := r.Withdraw(bob)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(500), got)
	uassert.Equal(t, int64(0), r.CreditOf(bob))
	uassert.Equal(t, int64(2000), r.TotalOwed())
}

// Withdraw zeroes the credit before it reports it, so the second call of a
// reentrant pair finds nothing.
func TestWithdrawZeroesBeforeItPays(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)
	_, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)

	got, err := r.Withdraw(alice)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(1000), got)

	_, err = r.Withdraw(alice)
	uassert.ErrorIs(t, err, ErrNothingToWithdraw)

	_, err = r.Withdraw(carol)
	uassert.ErrorIs(t, err, ErrNothingToWithdraw, "an address owed nothing withdraws nothing")

	uassert.Equal(t, int64(1000), r.EarnedBy(alice), "earnings outlive the withdrawal")
	uassert.Equal(t, int64(0), r.CreditOf(alice))
}

// IsActive is strict on both sides: active at paidThrough-1, not at
// paidThrough.
func TestIsActiveFlipsAtTheRightHeight(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)
	_, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)
	p := planOf(t, r, id)

	tests := []struct {
		name string
		now  int64
		want bool
	}{
		{"the block it was bought in", 500, true},
		{"one before the end", 599, true},
		{"the end itself", 600, false},
		{"after", 601, false},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, p.IsActive(bob, tt.now), tt.name)
	}

	uassert.False(t, p.IsActive(carol, 500), "an address that never paid is never active")
	uassert.Equal(t, int64(600), p.PaidThrough(bob))
	uassert.Equal(t, int64(0), p.PaidThrough(carol))
	uassert.Equal(t, 1, p.ActiveCount(599))
	uassert.Equal(t, 0, p.ActiveCount(600))
}

func TestCloseStopsNewMoneyAndNotPaidTime(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)
	_, err := r.Subscribe(id, bob, 1000, 500)
	urequire.NoError(t, err)

	uassert.ErrorIs(t, r.Close(id, bob), ErrNotCreator)
	urequire.NoError(t, r.Close(id, alice))
	uassert.ErrorIs(t, r.Close(id, alice), ErrAlreadyClosed)

	_, err = r.Subscribe(id, carol, 1000, 501)
	uassert.ErrorIs(t, err, ErrPlanClosed)

	p := planOf(t, r, id)
	uassert.False(t, p.Open)
	uassert.True(t, p.IsActive(bob, 599), "a closed plan does not take back a paid period")

	uassert.ErrorIs(t, r.Reopen(id, bob), ErrNotCreator)
	urequire.NoError(t, r.Reopen(id, alice))
	uassert.ErrorIs(t, r.Reopen(id, alice), ErrAlreadyOpen)

	_, err = r.Subscribe(id, carol, 1000, 501)
	uassert.NoError(t, err)
}

func TestNothingWorksOnAPlanThatIsNotThere(t *testing.T) {
	r := NewRegistry()
	_, err := r.Subscribe(4242, bob, 1000, 500)
	uassert.ErrorIs(t, err, ErrNoPlan)
	uassert.ErrorIs(t, r.Close(4242, alice), ErrNoPlan)
	uassert.ErrorIs(t, r.Reopen(4242, alice), ErrNoPlan)

	_, ok := r.Get(4242)
	uassert.False(t, ok)
}

func TestOnePaymentCannotBuyUnboundedTime(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1, MaxPeriodBlocks)

	_, err := r.Subscribe(id, bob, MaxPeriodsPerPayment+1, 500)
	uassert.ErrorIs(t, err, ErrTooManyPeriods)
	uassert.Equal(t, int64(0), planOf(t, r, id).PaidThrough(bob))

	// The ceiling itself is accepted, and the product is the one place the
	// naive arithmetic would have wrapped.
	pay, err := r.Subscribe(id, bob, MaxPeriodsPerPayment, 500)
	urequire.NoError(t, err)
	uassert.Equal(t, 500+MaxPeriodsPerPayment*MaxPeriodBlocks, pay.PaidThrough)
}

func TestSupportersAreDistinctAndInFirstPaymentOrder(t *testing.T) {
	r := NewRegistry()
	id := plan(t, r, 1000, 100)

	_, err := r.Subscribe(id, carol, 1000, 500)
	urequire.NoError(t, err)
	_, err = r.Subscribe(id, bob, 1000, 501)
	urequire.NoError(t, err)
	_, err = r.Subscribe(id, carol, 1000, 502)
	urequire.NoError(t, err)

	p := planOf(t, r, id)
	got := p.Supporters()
	urequire.Equal(t, 2, len(got))
	uassert.Equal(t, carol.String(), got[0].String(), "first payment wins the first slot")
	uassert.Equal(t, bob.String(), got[1].String())
	uassert.Equal(t, 2, p.SupporterCount())

	// The slice handed out is a copy: writing to it cannot reach the plan.
	got[0] = bob
	uassert.Equal(t, carol.String(), p.Supporters()[0].String())
}

func TestEarningsAccumulateAcrossPlansAndSupporters(t *testing.T) {
	r := NewRegistry()
	first := plan(t, r, 1000, 100)
	second := plan(t, r, 2000, 200)

	_, err := r.Subscribe(first, bob, 1000, 500)
	urequire.NoError(t, err)
	_, err = r.Subscribe(second, carol, 4000, 500)
	urequire.NoError(t, err)

	uassert.Equal(t, int64(5000), r.EarnedBy(alice))
	uassert.Equal(t, int64(5000), r.CreditOf(alice))
	uassert.Equal(t, int64(1000), planOf(t, r, first).Received)
	uassert.Equal(t, int64(4000), planOf(t, r, second).Received)
	uassert.Equal(t, 2, r.Count())
}

func TestListIsNewestFirst(t *testing.T) {
	r := NewRegistry()
	first := plan(t, r, 1000, 100)
	second := plan(t, r, 1000, 100)
	third := plan(t, r, 1000, 100)

	got := r.List(1, 10)
	urequire.Equal(t, 3, len(got))
	uassert.Equal(t, uint64(third), uint64(got[0].ID))
	uassert.Equal(t, uint64(second), uint64(got[1].ID))
	uassert.Equal(t, uint64(first), uint64(got[2].ID))
	uassert.Equal(t, 2, r.Pages(2))
	uassert.Equal(t, 0, len(r.List(9, 10)))
}

func TestURLsStripTheChainDomain(t *testing.T) {
	uassert.Equal(t, "/r/moul/x/social/patron/v0", RealmURL("gno.land/r/moul/x/social/patron/v0"))
	uassert.Equal(t, "/r/a/b:plan/7", PlanURL("gno.land/r/a/b", 7))
}

zerowidth_test.gno

package patron

import "testing"

// Finding 325-input-validation-1 (review run 001-cd0b6a9).
//
// A validator that calls a field required must agree with the escaper its own
// render runs. strings.TrimSpace uses unicode.IsSpace, which does NOT include
// U+200B and the rest of the bidi and zero-width set, while every escaper on
// the output side runs chain/markdown.StripBidiAndZeroWidth, which does. So a
// value made only of those characters passes validation and renders as
// nothing: a required field that is blank on the page.
//
// The cases below are the invariant, not the implementation. A value the
// validator accepts must still be non-empty after the stripper.
func TestValidatorsAgreeWithTheEscaper(t *testing.T) {
	// One per class the stripper removes, so a fix that handles only
	// U+200B does not pass.
	blank := []string{
		"\u200b\u200b\u200b",   // ZWSP
		"\u200d",                // ZWJ
		"\u200e",                // LRM
		"\u202e",                // RLO
		"\u2066\u2069",          // LRI PDI
		"\ufeff",                // BOM
		" \u200b \u200b ",        // mixed with real spaces
	}
	// These must stay valid: the stripper removes the marks and leaves text.
	ok := []string{
		"a",
		"a\u200bb",
		"  padded  ",
	}

	for _, s := range blank {
		if ValidTitle(s) {
			t.Errorf("ValidTitle(%q) is true, but the render strips it to empty", s)
		}
	}
	for _, s := range ok {
		if !ValidTitle(s) {
			t.Errorf("ValidTitle(%q) is false, but it renders as real text", s)
		}
	}

}