Playground
bounded_test.gno
package patron
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
)
// Finding 325-cost-at-caps-1. A plan page rendered every all-time supporter.
// Subscribe is permissionless and nothing ever removes a supporter, so the
// cheapest way to make somebody's page expensive was to subscribe from many
// addresses.
//
// Both comparison points are above the cap on purpose: comparing a count below
// it with one above it measures the cap arriving, not the page being bounded.
// The loops are inline because testing.SetRealm is call-frame scoped.
func TestAPlanPageIsBoundedByWhatItShows(cur realm, t *testing.T) {
reset()
id := open(cur, t)
for i := 0; i < 40; i++ {
pay(price)
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("sub" + strconv.Itoa(i))))
Subscribe(cross(cur), id)
}
small := Render("plan/" + strconv.FormatInt(id, 10))
for i := 40; i < 200; i++ {
pay(price)
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("sub" + strconv.Itoa(i))))
Subscribe(cross(cur), id)
}
big := Render("plan/" + strconv.FormatInt(id, 10))
rowsSmall := strings.Count(small, "\n|")
rowsBig := strings.Count(big, "\n|")
if rowsSmall == 0 {
t.Fatal("no table rows rendered at all, so this test is measuring nothing")
}
if rowsBig > rowsSmall {
t.Errorf("the plan page grew from %d rows to %d when the supporters went from 40 to 200: "+
"every reader pays for every address that ever subscribed", rowsSmall, rowsBig)
}
}
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/patron/v0" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914348 max_deposit = "15000000ugnot"
patron.gno
// Package patron is recurring support for a builder, on chain.
//
// A creator opens a plan with a price per period and a period measured in
// blocks. A supporter attaches ugnot to [Subscribe] and buys whole periods of
// it. Anybody can ask at any height whether a given address is still active,
// which is the one question a tip cannot answer.
//
// # There is no cron on chain, so a renewal is a pull and not a push
//
// Nothing in this realm can charge anybody. A renewal happens because the
// supporter sends another payment, never because a timer fired: there is no
// scheduler here, and there is no way to write one, since a native coin
// cannot be pulled at all. A reader arriving from web2 expects a standing
// mandate on a card and there is nothing of the kind, anywhere on this chain.
//
// # What this adds over the tip jar
//
// gno.land/r/moul/x/daily/tipjar is the one-shot version and is already live:
// one payment, a leaderboard, and then nothing. The recurrence is the whole
// difference. A plan has a price and a period, a payment buys whole periods
// of it, renewing early never discards time already paid for, and the realm
// answers "is this address active right now" at any height. It is the one app
// in the x/social family that produces a recurring write rather than a
// one-off.
//
// # Earnings are credited at payment time, not streamed
//
// The creator can withdraw the full price the instant it is paid. A supporter
// who stops being active is NOT refunded, and no part of a paid period ever
// comes back. That is a deliberate v0 limitation: escrowed streaming, where
// the creator claims only what has elapsed and the supporter cancels and
// reclaims the rest, needs a claim schedule and a refund path, and that is a
// larger realm than this one rather than a flag on it.
//
// # Money leaves by pull
//
// Both halves of what this realm owes, a creator's earnings and a supporter's
// change, land in one credit ledger and leave through [Withdraw]. The credit
// is zeroed before any coin moves, and the realm never loops over payees: one
// unpayable address would otherwise fail the whole batch and hand a griefer a
// cheap denial of service.
//
// # v0 ships no token
//
// Deliberately, and the README says why: a creator coin minted per period
// paid is easy, and the sink is not, because what it would be redeemed for is
// a promise made off chain.
package patron
import (
"chain"
"chain/banker"
"chain/runtime"
"strconv"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/envelope/v0"
pt "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/patron/v0"
)
// realmPath is this realm's own path, the one its gnomod.toml module line
// declares. It is written out rather than read from the frame, because a
// plain read exported by a realm reports the CALLER and would build every
// link against whoever asked.
const realmPath = "gno.land/r/moul/x/social/patron/v0"
// denom is the only coin this realm handles.
const denom = "ugnot"
// plans holds every plan and the credit ledger. A redeploy wipes it, which is
// the trade `private = true` makes: see gnomod.toml.
var plans = pt.NewRegistry()
// Open creates a plan and returns its id. Anyone may open one, and opening
// one costs nothing beyond gas and the storage deposit.
//
// pricePerPeriod is in ugnot and must be at least one: a free plan is a tip
// jar, not a subscription. periodBlocks is a period in BLOCKS, bounded both
// ways by the engine, because height is the clock consensus agrees on and a
// block timestamp is not something to build a billing cliff out of.
func Open(cur realm, title, description string, pricePerPeriod, periodBlocks int64) int64 {
who := caller(cur)
id, err := plans.Open(who, title, description, pricePerPeriod, periodBlocks)
if err != nil {
panic(err.Error())
}
chain.Emit("Open",
"id", id.String(),
"creator", who.String(),
"price", strconv.FormatInt(pricePerPeriod, 10),
"period", strconv.FormatInt(periodBlocks, 10))
return int64(id)
}
// Subscribe buys whole periods on a plan with the ugnot attached to the call,
// and returns the caller's new paid-through height.
//
// Attach the coins with -send: a payment short of one period is refused, and
// the remainder under one period is credited back to the caller rather than
// kept, so an overpayment is change and never a silent fee. Take it back with
// [Withdraw].
//
// # It has to be called directly by a user, and that is not a style choice
//
// The envelope is what the SIGNER attached to the transaction. A realm the
// user called has already received those coins itself, and could then call in
// here as many times as it liked against one payment, so the caller is
// checked before the envelope is read. The same property means a realm cannot
// forward an envelope it was handed (`NewBanker` requires the previous frame
// to be a user call), and that `maketx run` cannot reach this function at all,
// because a run script is itself a code realm. Use `maketx call -send`.
func Subscribe(cur realm, planID int64) int64 {
// The frame is read here rather than through caller(), because this
// function asks the previous frame two questions and the order of them is
// the whole guard: is the token live, is the caller a user, and only then
// what did they send.
if !cur.IsCurrent() {
panic("spoofed realm: cur is not the live crossing frame")
}
prev := cur.Previous()
if !prev.IsUserCall() {
panic("patron: Subscribe must be called directly by a user with maketx call -send, " +
"not through another realm and not from maketx run")
}
who := prev.Address()
id := store.ID(planID)
p := mustGet(id)
if !p.Open {
panic(pt.ErrPlanClosed.Error())
}
// RequireAtLeast names both numbers when the envelope falls short, which
// is the difference between a caller fixing their command and a caller
// opening their wallet.
sent := envelope.RequireAtLeast(denom, p.PricePerPeriod)
pay, err := plans.Subscribe(id, who, sent, runtime.ChainHeight())
if err != nil {
panic(err.Error())
}
chain.Emit("Subscribe",
"id", id.String(),
"supporter", who.String(),
"periods", strconv.FormatInt(pay.Periods, 10),
"spent", strconv.FormatInt(pay.Spent, 10),
"change", strconv.FormatInt(pay.Change, 10),
"paidThrough", strconv.FormatInt(pay.PaidThrough, 10))
return pay.PaidThrough
}
// Close stops a plan taking new subscriptions. Creator only.
//
// Everything already paid for runs to its own paid-through height. Closing a
// plan is not a way to take a period back.
func Close(cur realm, planID int64) {
who := caller(cur)
id := store.ID(planID)
if err := plans.Close(id, who); err != nil {
panic(err.Error())
}
chain.Emit("Close", "id", id.String(), "by", who.String())
}
// Reopen lets a closed plan take subscriptions again. Creator only.
func Reopen(cur realm, planID int64) {
who := caller(cur)
id := store.ID(planID)
if err := plans.Reopen(id, who); err != nil {
panic(err.Error())
}
chain.Emit("Reopen", "id", id.String(), "by", who.String())
}
// Withdraw pays the caller everything this realm owes them and returns the
// amount: a creator's earnings, a supporter's change, or both at once.
//
// The credit is zeroed by the engine before a coin moves, so a recipient that
// calls straight back in finds nothing left to take.
func Withdraw(cur realm) int64 {
who := caller(cur)
amount, err := plans.Withdraw(who)
if err != nil {
panic(err.Error())
}
banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(
cur.Address(), who, chain.NewCoins(chain.NewCoin(denom, amount)))
chain.Emit("Withdraw", "to", who.String(), "amount", strconv.FormatInt(amount, 10))
return amount
}
// Get returns a plan's fields.
//
// It returns a tuple rather than the stored record: handing out a pointer to
// realm state is a live mutation handle, and this realm is private, so an
// importer retaining one of its objects would be a runtime panic rather than
// a design debate.
func Get(planID int64) (creator address, title, description string, pricePerPeriod, periodBlocks int64, open bool) {
p := mustGet(store.ID(planID))
return p.Creator, p.Title, p.Description, p.PricePerPeriod, p.PeriodBlocks, p.Open
}
// Count is how many plans exist.
func Count() int { return plans.Count() }
// IsActive reports whether who is paid up on this plan at the current height.
//
// Active means now < paidThrough, strictly: an address paid through height h
// is active at h-1 and not at h.
func IsActive(planID int64, who address) bool {
return mustGet(store.ID(planID)).IsActive(who, runtime.ChainHeight())
}
// PaidThrough is the height who stops being active at on this plan, or zero
// if they never paid.
func PaidThrough(planID int64, who address) int64 {
return mustGet(store.ID(planID)).PaidThrough(who)
}
// SupporterCount is how many distinct addresses have ever paid this plan,
// active or not.
func SupporterCount(planID int64) int {
return mustGet(store.ID(planID)).SupporterCount()
}
// Supporters is every address that has ever paid this plan, in first-payment
// order. It is a copy, not the stored slice.
func Supporters(planID int64) []address {
return mustGet(store.ID(planID)).Supporters()
}
// EarnedBy is the lifetime ugnot credited to creator across every plan,
// whether or not it has been withdrawn.
func EarnedBy(creator address) int64 { return plans.EarnedBy(creator) }
// CreditOf is what addr can withdraw right now.
func CreditOf(addr address) int64 { return plans.CreditOf(addr) }
// TotalOwed is everything this realm owes, which is what it must keep in
// reserve at its own address.
func TotalOwed() int64 { return plans.TotalOwed() }
// mustGet reads a plan or aborts naming it.
func mustGet(id store.ID) *pt.Plan {
p, ok := plans.Get(id)
if !ok {
panic("patron: plan #" + id.String() + " not found")
}
return p
}
// caller is the address that called us, checked the one way that is safe.
func caller(cur realm) address {
if !cur.IsCurrent() {
panic("spoofed realm: cur is not the live crossing frame")
}
return cur.Previous().Address()
}
patron_test.gno
package patron
import (
"strconv"
"strings"
"testing"
"chain"
"chain/banker"
"chain/runtime"
pt "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/patron/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const (
price = int64(1000000) // 1 GNOT per period
period = int64(100) // blocks
)
var (
alice = testutils.TestAddress("alice") // the creator, throughout
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
realmAddr = chain.PackageAddress(realmPath)
)
// reset clears realm state. Realm globals live for the whole test binary, so
// everything a later test or the Render tests read starts here.
func reset() { plans = pt.NewRegistry() }
// pay stages a payment the way the chain does: the coins land at the realm's
// address before a line of its code runs, and OriginSend is what the crossing
// function then reads.
func pay(amount int64) {
testing.IssueCoins(realmAddr, chain.Coins{{denom, amount}})
testing.SetOriginSend(chain.Coins{{denom, amount}})
}
// open creates a plan as alice. SetRealm is call-frame scoped, so the account
// is switched here and then crossed from here, never from a helper that does
// not itself cross.
func open(cur realm, t *testing.T) int64 {
t.Helper()
testing.SetRealm(testing.NewUserRealm(alice))
return Open(cross(cur), "monthly support", "a plan with a | pipe in it", price, period)
}
func TestOpenStoresWhatItWasGiven(cur realm, t *testing.T) {
reset()
id := open(cur, t)
creator, title, desc, p, blocks, isOpen := Get(id)
uassert.Equal(t, alice.String(), creator.String())
uassert.Equal(t, "monthly support", title)
uassert.Equal(t, "a plan with a | pipe in it", desc)
uassert.Equal(t, price, p)
uassert.Equal(t, period, blocks)
uassert.True(t, isOpen)
uassert.Equal(t, 1, Count())
uassert.Equal(t, 0, SupporterCount(id))
}
func TestOpenRefusesAFreePlanAndASillyPeriod(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "at least one ugnot per period", func() {
Open(cross(cur), "free", "", 0, period)
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "period out of range", func() {
Open(cross(cur), "instant", "", price, 0)
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "period out of range", func() {
Open(cross(cur), "forever", "", price, pt.MaxPeriodBlocks+1)
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "title is empty", func() {
Open(cross(cur), " ", "", price, period)
})
uassert.Equal(t, 0, Count())
}
// One period, paid exactly, credited to the creator at payment time and
// withdrawable as real coins in this same test, because the bank does not
// carry over between test functions.
func TestOnePeriodIsBoughtAndTheCreatorIsPaid(cur realm, t *testing.T) {
reset()
id := open(cur, t)
start := runtime.ChainHeight()
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
through := Subscribe(cross(cur), id)
uassert.Equal(t, start+period, through)
uassert.Equal(t, start+period, PaidThrough(id, bob))
uassert.True(t, IsActive(id, bob))
uassert.Equal(t, 1, SupporterCount(id))
uassert.Equal(t, price, EarnedBy(alice))
uassert.Equal(t, price, CreditOf(alice))
uassert.Equal(t, int64(0), CreditOf(bob), "an exact payment leaves no change")
uassert.Equal(t, price, TotalOwed())
ro := banker.NewReadonlyBanker()
before := ro.GetCoin(alice, denom)
testing.SetRealm(testing.NewUserRealm(alice))
got := Withdraw(cross(cur))
uassert.Equal(t, price, got)
uassert.Equal(t, price, ro.GetCoin(alice, denom)-before, "the creator was really paid")
uassert.Equal(t, int64(0), CreditOf(alice))
uassert.Equal(t, price, EarnedBy(alice), "earnings outlive the withdrawal")
uassert.Equal(t, int64(0), TotalOwed())
}
func TestThreePeriodsAtOnce(cur realm, t *testing.T) {
reset()
id := open(cur, t)
start := runtime.ChainHeight()
pay(3 * price)
testing.SetRealm(testing.NewUserRealm(bob))
through := Subscribe(cross(cur), id)
uassert.Equal(t, start+3*period, through)
uassert.Equal(t, 3*price, CreditOf(alice))
uassert.Equal(t, int64(0), CreditOf(bob))
}
// Renewing before the lapse extends from paidThrough, so the time already
// paid for is still there afterwards.
func TestRenewingEarlyExtendsRatherThanRestarts(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
first := Subscribe(cross(cur), id)
// Ten blocks in, with ninety still paid for.
testing.SkipHeights(10)
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
second := Subscribe(cross(cur), id)
uassert.Equal(t, first+period, second, "the second period starts where the first ended")
uassert.True(t, second > runtime.ChainHeight()+period,
"more than one period is left, which is the point")
uassert.Equal(t, 1, SupporterCount(id), "renewing is not a second supporter")
}
// Renewing after a lapse starts from now: the gap was never paid for.
func TestRenewingAfterALapseStartsFromNow(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
Subscribe(cross(cur), id)
testing.SkipHeights(500)
uassert.False(t, IsActive(id, bob), "the first period lapsed long ago")
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
second := Subscribe(cross(cur), id)
uassert.Equal(t, runtime.ChainHeight()+period, second)
uassert.True(t, IsActive(id, bob))
}
// IsActive flips at the block the period ends on, and not a block either side.
func TestIsActiveFlipsAtTheRightHeight(cur realm, t *testing.T) {
reset()
id := open(cur, t)
start := runtime.ChainHeight()
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
Subscribe(cross(cur), id)
testing.SetHeight(start + period - 1)
uassert.True(t, IsActive(id, bob), "the last block of the period")
testing.SetHeight(start + period)
uassert.False(t, IsActive(id, bob), "the first block after it")
uassert.False(t, IsActive(id, carol), "an address that never paid is never active")
uassert.Equal(t, int64(0), PaidThrough(id, carol))
}
func TestAPaymentShortOfOnePeriodIsRefused(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(price - 1)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "this call costs at least", func() {
Subscribe(cross(cur), id)
})
uassert.Equal(t, int64(0), PaidThrough(id, bob))
uassert.Equal(t, int64(0), EarnedBy(alice))
uassert.Equal(t, 0, SupporterCount(id))
}
// The remainder under one period is the supporter's, not the realm's, and it
// comes back out as real coins.
func TestChangeIsCreditedBackAndWithdrawable(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(2*price + 250000)
testing.SetRealm(testing.NewUserRealm(bob))
Subscribe(cross(cur), id)
uassert.Equal(t, int64(250000), CreditOf(bob), "the change is the supporter's")
uassert.Equal(t, 2*price, CreditOf(alice))
uassert.Equal(t, 2*price+250000, TotalOwed(), "every ugnot in is owed to somebody")
ro := banker.NewReadonlyBanker()
before := ro.GetCoin(bob, denom)
testing.SetRealm(testing.NewUserRealm(bob))
got := Withdraw(cross(cur))
uassert.Equal(t, int64(250000), got)
uassert.Equal(t, int64(250000), ro.GetCoin(bob, denom)-before)
uassert.Equal(t, int64(0), CreditOf(bob))
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "nothing to withdraw", func() { Withdraw(cross(cur)) })
}
func TestWithdrawRefusesSomebodyOwedNothing(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(carol))
uassert.AbortsContains(t, cur, "nothing to withdraw", func() { Withdraw(cross(cur)) })
}
// A realm that the user called holds the coins itself and could subscribe
// over and over against one payment. The guard runs before the envelope is
// read, so it cannot.
func TestOnlyAUserCanSubscribe(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(price)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/g1relay/forwarder"))
uassert.AbortsContains(t, cur, "must be called directly by a user", func() {
Subscribe(cross(cur), id)
})
uassert.Equal(t, int64(0), EarnedBy(alice))
}
func TestCloseAndReopenAreTheCreatorsAlone(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
Subscribe(cross(cur), id)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "only the plan's creator", func() { Close(cross(cur), id) })
testing.SetRealm(testing.NewUserRealm(alice))
Close(cross(cur), id)
_, _, _, _, _, isOpen := Get(id)
uassert.False(t, isOpen)
uassert.True(t, IsActive(id, bob), "closing does not take back a paid period")
pay(price)
testing.SetRealm(testing.NewUserRealm(carol))
uassert.AbortsContains(t, cur, "closed to new subscriptions", func() {
Subscribe(cross(cur), id)
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "already closed", func() { Close(cross(cur), id) })
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "only the plan's creator", func() { Reopen(cross(cur), id) })
testing.SetRealm(testing.NewUserRealm(alice))
Reopen(cross(cur), id)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "already open", func() { Reopen(cross(cur), id) })
pay(price)
testing.SetRealm(testing.NewUserRealm(carol))
Subscribe(cross(cur), id)
uassert.Equal(t, 2, SupporterCount(id))
}
func TestAPlanThatIsNotThere(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "plan #4242 not found", func() {
Subscribe(cross(cur), 4242)
})
uassert.PanicsContains(t, cur, "plan #4242 not found", func() { Count(); IsActive(4242, bob) })
}
func TestSupportersAreDistinctAndInFirstPaymentOrder(cur realm, t *testing.T) {
reset()
id := open(cur, t)
pay(price)
testing.SetRealm(testing.NewUserRealm(carol))
Subscribe(cross(cur), id)
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
Subscribe(cross(cur), id)
pay(price)
testing.SetRealm(testing.NewUserRealm(carol))
Subscribe(cross(cur), id)
got := Supporters(id)
urequire.Equal(t, 2, len(got))
uassert.Equal(t, carol.String(), got[0].String())
uassert.Equal(t, bob.String(), got[1].String())
}
// TestRender uses uassert rather than an Example because every view contains
// consecutive blank lines, which gno collapses inside an // Output: block.
func TestRender(cur realm, t *testing.T) {
reset()
empty := Render("")
uassert.True(t, strings.Contains(empty, "No plans yet."), empty)
uassert.True(t, strings.Contains(empty, "no cron on chain"), "the index says it: "+empty)
testing.SetRealm(testing.NewUserRealm(alice))
id := Open(cross(cur), "a | pipe and [a link](x)", "about **everything**", price, period)
pay(price)
testing.SetRealm(testing.NewUserRealm(bob))
Subscribe(cross(cur), id)
index := Render("")
uassert.False(t, strings.Contains(index, "| a | pipe"),
"a raw pipe would open a column: "+index)
uassert.True(t, strings.Contains(index, "a \\| pipe and \\[a link\\]\\(x\\)"),
"the title is escaped once in the listing, pipe included: "+index)
uassert.True(t, strings.Contains(index, "["+strconv.FormatInt(id, 10)+"](/r/moul/x/social/patron/v0:plan/"),
"the link text is the plan number, which is ours and not the caller's: "+index)
uassert.True(t, strings.Contains(index, "func=Open"), "the index offers the transaction")
uassert.True(t, strings.Contains(index, "1 of 1"), "one active of one supporter: "+index)
sid := strconv.FormatInt(id, 10)
page := Render("plan/" + sid)
uassert.True(t, strings.Contains(page, "# Plan #"+sid))
// A heading is prose, so ui.Inline escapes the link syntax and leaves the
// pipe alone: a pipe only means something inside a table.
uassert.True(t, strings.Contains(page, "# Plan #"+sid+": a | pipe and \\[a link\\]\\(x\\)"),
"the title is escaped in the heading too: "+page)
uassert.True(t, strings.Contains(page, "about \\*\\*everything\\*\\*"),
"the description is escaped: "+page)
uassert.True(t, strings.Contains(page, "func=Subscribe"))
uassert.True(t, strings.Contains(page, ".send="+strconv.FormatInt(price, 10)+"ugnot"),
"the support link carries the price: "+page)
uassert.True(t, strings.Contains(page, "func=Close"))
testing.SetRealm(testing.NewUserRealm(alice))
Close(cross(cur), id)
closed := Render("plan/" + sid)
uassert.True(t, strings.Contains(closed, "takes no new subscriptions"), closed)
uassert.False(t, strings.Contains(closed, "func=Subscribe"),
"a closed plan offers no payment: "+closed)
uassert.Equal(t, "# Patron\nNo plan #4242", Render("plan/4242"))
uassert.Equal(t, "# Patron\nNot a plan id: nope", Render("plan/nope"))
uassert.True(t, strings.HasPrefix(Render("elsewhere"), "# Not found"))
// A page past the end is an empty listing, not a panic.
uassert.True(t, strings.Contains(Render("?page=99"), "No plans yet."))
uassert.True(t, strings.Contains(Render("?page=nonsense"), "a \\| pipe"),
"an unreadable page number falls back to the first")
}
render.gno
package patron
import (
"strconv"
"strings"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/num/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/txlink/v0"
pt "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/patron/v0"
)
// pageSize is how many plans the index lists at once.
const pageSize = 20
// titleWidth is how much of a plan's title a listing shows.
const titleWidth = 40
// Render routes two views: the index and one plan.
func Render(path string) string {
req := realmpath.Parse(path)
switch {
case strings.HasPrefix(req.Path, "plan/"):
return renderPlan(strings.TrimPrefix(req.Path, "plan/"))
case req.Path == "":
return renderIndex(req)
default:
return md.H1("Not found") + "No such view: " + ui.Inline(req.Path)
}
}
func renderIndex(req *realmpath.Request) string {
now := runtime.ChainHeight()
out := md.H1("Patron")
out += "Recurring support for a builder. A creator opens a plan with a price per " +
"period and a period measured in blocks, and a supporter buys whole periods of " +
"it with " + md.InlineCode("ugnot") + ".\n\n"
out += md.Blockquote("There is no cron on chain, so a renewal is a pull and not a " +
"push: nothing here can charge anybody. A supporter renews by paying again, and " +
"renewing early never loses time already paid for.") + "\n"
stats := ui.NewTable("plans", "owed to creators and supporters", "block")
stats.Row(
strconv.Itoa(plans.Count()),
num.GNOTf(plans.TotalOwed()),
strconv.FormatInt(now, 10),
)
out += stats.String()
out += md.H2("Plans")
out += planTable(plans.List(pageNum(req), pageSize), now)
out += "\n" + ui.Action("➕ Open a plan", "Open",
"title", "", "description", "", "pricePerPeriod", "", "periodBlocks", "") +
" · " + ui.Action("💰 Withdraw what I am owed", "Withdraw") + "\n"
out += md.H2("What it does not do")
out += md.BulletList([]string{
"**It does not charge anybody.** A renewal is a payment the supporter signs.",
"**It does not stream.** A creator is credited the whole price at the moment " +
"it is paid, so a supporter who stops being active is not refunded and no " +
"part of a paid period comes back. Escrowed streaming needs a claim " +
"schedule and a refund path, which is the v1.",
"**It does not issue a token.** Minting a creator coin per period paid is " +
"easy; the sink is not, because what it would be redeemed for is a promise " +
"made off chain.",
})
return out
}
func renderPlan(raw string) string {
id, ok := store.ParseID(raw)
if !ok {
return md.H1("Patron") + "Not a plan id: " + ui.Inline(raw)
}
p, found := plans.Get(id)
if !found {
return md.H1("Patron") + "No plan #" + id.String()
}
now := runtime.ChainHeight()
out := md.H1("Plan #" + id.String() + ": " + ui.Inline(p.Title))
if p.Description != "" {
out += md.Blockquote(ui.Inline(p.Description)) + "\n"
}
status := "open"
if !p.Open {
status = "closed to new subscriptions"
}
facts := ui.NewTable("creator", "price per period", "period", "status")
facts.Row(
ui.Addr(p.Creator),
num.GNOTf(p.PricePerPeriod),
strconv.FormatInt(p.PeriodBlocks, 10)+" blocks",
status,
)
out += facts.String()
if p.Open {
// The link carries the send amount, so the price is not something a
// supporter has to copy out of the table and retype.
out += md.Link(
"💜 Support for one period ("+num.GNOTf(p.PricePerPeriod)+")",
txlink.Realm(realmPath).NewLink("Subscribe").
AddArgs("planID", id.String()).
SetSend(strconv.FormatInt(p.PricePerPeriod, 10)+denom).
URL(),
) + "\n\n"
out += "Paying " + md.InlineCode("n") + " times the price buys " +
md.InlineCode("n") + " periods at once. Anything left over under one " +
"period is credited back to you, not kept: take it with " +
md.InlineCode("Withdraw") + ".\n"
} else {
out += ui.Empty("This plan takes no new subscriptions. Anything already paid " +
"for runs to its own block.")
}
out += md.H2("Supporters")
out += supporterTable(p, now)
out += md.H2("Creator")
out += "Earned across every plan: " + md.Bold(num.GNOTf(plans.EarnedBy(p.Creator))) +
" · withdrawable now: " + md.Bold(num.GNOTf(plans.CreditOf(p.Creator))) + "\n\n"
out += ui.Action("🚪 Close", "Close", "planID", id.String()) +
" · " + ui.Action("🔓 Reopen", "Reopen", "planID", id.String()) +
" · " + ui.Action("💰 Withdraw", "Withdraw") + "\n\n"
out += md.Link("← every plan", pt.RealmURL(realmPath)) + "\n"
return out
}
// planTable lists plans.
//
// The link text is the plan NUMBER and not its title, which is the one thing
// to copy from here. md.Link escapes its text with the inline escaper, and the
// inline escaper does not touch a pipe, because a pipe means nothing in a
// sentence: a user title carried inside a link inside a table cell therefore
// still opens a column. So the title gets its own cell and goes through
// ui.Cell, which is the escaper that knows it is in a table. It is truncated
// first with ui.ShortN, which does not escape, so the cut can never strand a
// backslash that the escaper had just inserted.
func planTable(items []pt.Listing, now int64) string {
t := ui.NewTable("#", "plan", "creator", "per period", "period", "supporters", "")
for _, it := range items {
mark := "🟢"
if !it.Plan.Open {
mark = "🔒"
}
t.Row(
md.Link(it.ID.String(), pt.PlanURL(realmPath, it.ID)),
ui.Cell(ui.ShortN(it.Plan.Title, titleWidth, 0)),
ui.Addr(it.Plan.Creator),
num.GNOTf(it.Plan.PricePerPeriod),
strconv.FormatInt(it.Plan.PeriodBlocks, 10)+" blocks",
strconv.Itoa(it.Plan.ActiveCount(now))+" of "+strconv.Itoa(it.Plan.SupporterCount()),
mark,
)
}
return t.OrEmpty("No plans yet.")
}
// supporterTable lists a plan's supporters.
//
// Finding 325-cost-at-caps-1: this rendered every all-time supporter.
// Subscribe is permissionless and nothing ever removes a supporter, so the
// page every reader pays for grew without a bound anybody controls, and the
// cheapest way to make it expensive was to subscribe from many addresses.
func supporterTable(p *pt.Plan, now int64) string {
all := p.Supporters()
shown := all
if len(shown) > pageSize {
shown = shown[len(shown)-pageSize:]
}
t := ui.NewTable("supporter", "paid through block", "active")
for _, who := range shown {
active := "no"
if p.IsActive(who, now) {
active = "yes"
}
t.Row(ui.Addr(who), strconv.FormatInt(p.PaidThrough(who), 10), active)
}
out := t.OrEmpty("Nobody supports this plan yet.")
if len(all) > pageSize {
out += md.Italic("Showing the newest "+strconv.Itoa(pageSize)+" of "+
strconv.Itoa(len(all))+" supporters.") + "\n"
}
return out
}
// pageNum reads ?page= and falls back to the first page for anything it
// cannot read, which is the only answer a Render can give: there is nobody to
// report an error to.
func pageNum(req *realmpath.Request) int {
n, err := strconv.Atoi(req.Query.Get("page"))
if err != nil || n < 1 {
return 1
}
return n
}