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.

render.gno

26.90 Kb · 513 lines
  1package mandate
  2
  3import (
  4	"strconv"
  5	"strings"
  6	"time"
  7)
  8
  9// SourceRepo is where the source code is published, shown in the footer of
 10// every page.
 11const SourceRepo = "https://github.com/elangrr/mandate"
 12
 13// Network the copy-ready commands are pinned to.
 14const (
 15	ChainID = "onyx-1"
 16	Remote  = "https://rpc.onyx.testnets.gno.land:443"
 17)
 18
 19// Gas settings used in the commands. The chain charges the whole fee set,
 20// whatever gas is used, and accepts it when fee / gas wanted is at least
 21// the current gas price (1 ugnot per 1,000 gas on Onyx). Measured on a local
 22// chain: Offer and Subscribe use 7M to 10M gas, Pull 8M to 9M. Reads on
 23// Onyx cost more per object (the chain prices a read by its store's depth,
 24// and Onyx's store is far larger), so gas wanted keeps about 2x headroom.
 25// The Pull fee counts against the session's spend limit (see FeeAllowance).
 26const (
 27	callGas = "-gas-fee 100000ugnot -gas-wanted 60000000"
 28	pullGas = "-gas-fee 20000ugnot -gas-wanted 20000000"
 29)
 30
 31// Render returns the gnoweb page for path, with the footer.
 32func Render(path string) string {
 33	return renderPage(path) + footer()
 34}
 35
 36func footer() string {
 37	return "\n---\n\nBuilt on [gno.land](https://gno.land) · source code: [" + strings.TrimPrefix(SourceRepo, "https://") + "](" + SourceRepo + ")\n"
 38}
 39
 40func renderPage(raw string) string {
 41	path, query := raw, ""
 42	if i := strings.Index(raw, "?"); i >= 0 {
 43		path, query = raw[:i], raw[i+1:]
 44	}
 45	page := pageParam(query)
 46	from := intParam(query, "from", -1)
 47	parts := strings.Split(path, "/")
 48	switch {
 49	case path == "":
 50		return renderHome(from)
 51	case path == "plans":
 52		return renderAllPlans(page)
 53	case path == "help":
 54		return renderHelp()
 55	case len(parts) == 2 && parts[0] == "plan":
 56		id, err := strconv.ParseUint(parts[1], 10, 64)
 57		if err != nil {
 58			return renderNotFound()
 59		}
 60		return renderPlan(id, from)
 61	case len(parts) == 2 && parts[0] == "payer":
 62		a := address(parts[1])
 63		if !a.IsValid() {
 64			return renderNotFound()
 65		}
 66		return renderPayer(a, page)
 67	case len(parts) == 2 && parts[0] == "payee":
 68		a := address(parts[1])
 69		if !a.IsValid() {
 70			return renderNotFound()
 71		}
 72		return renderPayee(a, page)
 73	}
 74	return renderNotFound()
 75}
 76
 77func renderHome(from int) string {
 78	nPlans, nMandates, pulls, paid := Totals()
 79	var b strings.Builder
 80	b.WriteString("# Mandate\n\n")
 81	b.WriteString("**Subscriptions and direct debit on native GNOT.** A creator publishes a plan, such as 1 GNOT every week. ")
 82	b.WriteString("A supporter signs one permission from their own wallet: *at most this much, every period, through this realm only, until I cancel or it expires*. ")
 83	b.WriteString("The creator's collector then pulls each payment at the start of the period, and this realm checks who, how much and when before it forwards the coins.\n\n")
 84	b.WriteString("## The honest limits\n\n")
 85	b.WriteString("- **It is direct debit, not escrow.** Nothing is locked up front. A supporter can stop at any time, and a creator is only paid when a pull succeeds.\n")
 86	b.WriteString("- **A hard cap the supporter sets.** The chain never lets a pull take more than the session's spend limit per period: the plan's amount plus a fee allowance of " + formatUgnot(FeeAllowance) + ". ")
 87	b.WriteString("A dishonest creator could at worst burn that allowance as network fees; they can never take more, or pull more often.\n")
 88	b.WriteString("- **At most " + strconv.Itoa(MaxSessionsPerWallet) + " mandates per wallet**, because the chain allows " + strconv.Itoa(MaxSessionsPerWallet) + " session keys per account.\n")
 89	b.WriteString("- **Revoke any time.** Revoking the session on chain stops every pull at once. The realm cannot see a revoke, so a mandate still shows here as active until it is cancelled or expires: [how to stop a mandate](" + link("help") + ").\n")
 90	b.WriteString("- **One realm, nothing under it.** A session for this realm also covers any realm deployed under its path, so nothing will ever be deployed there.\n")
 91	b.WriteString("- No admin, no pause, no upgrade. The realm never holds funds: each payment goes straight to the creator in the same transaction.\n\n")
 92	b.WriteString("[How to use it, with every command](" + link("help") + ")\n\n")
 93	b.WriteString("## Numbers\n\n")
 94	b.WriteString("| Plans | Mandates ever recorded | Payments | Paid out |\n|---|---|---|---|\n")
 95	b.WriteString("| " + strconv.Itoa(nPlans) + " | " + strconv.Itoa(nMandates) + " | " + itoa(pulls) + " | " + formatUgnot(paid) + " |\n\n")
 96	b.WriteString("## Supporter pages\n\n")
 97	b.WriteString(plansWithSupporters(from))
 98	return b.String()
 99}
100
101// homeScanPlans is how many plans one home page walks. Each check reads only
102// the plan itself (its payment counters), never its supporters.
103const homeScanPlans = ScanLimit
104
105// plansWithSupporters lists, newest first, the plans that someone paid in
106// the current or the previous period, walking at most homeScanPlans plans
107// per page: plans nobody pays for (spam included) never fill this list, and
108// a "more" link continues the walk. A plan someone keeps paying for stays,
109// whatever the churn of its supporter list.
110func plansWithSupporters(from int) string {
111	var b strings.Builder
112	n := plans.Size()
113	if from < 0 || from >= n {
114		from = n - 1
115	}
116	rows := 0
117	i := from
118	now := time.Now().Unix()
119	var t strings.Builder
120	for walked := 0; i >= 0 && walked < homeScanPlans && rows < PageSize; i, walked = i-1, walked+1 {
121		_, v := plans.GetByIndex(i)
122		p := v.(*Plan)
123		if current, previous := p.paidWindows(now); current+previous == 0 {
124			continue
125		}
126		t.WriteString("| [#" + utoa(p.ID) + " " + escCell(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ") | " + price(p.Amount, p.Period) +
127			" | [" + short(p.Payee) + "](" + link("payee/"+p.Payee.String()) + ") | " + payingCell(p, now) +
128			" | " + itoa(p.Pulls) + " |\n")
129		rows++
130	}
131	if rows == 0 {
132		b.WriteString("No plan has been paid for in its current or last period")
133		if i >= 0 {
134			b.WriteString(" among those looked at")
135		}
136		b.WriteString(".\n\n")
137	} else {
138		b.WriteString("| Plan | Price | Creator | Payments this / last period | All payments |\n|---|---|---|---|---|\n")
139		b.WriteString(t.String() + "\n")
140	}
141	if i >= 0 {
142		b.WriteString("[More plans with supporters](" + link("") + "?from=" + strconv.Itoa(i) + ")\n\n")
143	}
144	b.WriteString("Only plans that someone has paid for are listed here. [All plans, newest first](" + link("plans") + ")\n")
145	return b.String()
146}
147
148func renderAllPlans(page int) string {
149	var b strings.Builder
150	b.WriteString("# All plans\n\nNewest first, including plans nobody has paid for yet. [Back to Mandate](" + link("") + ")\n\n")
151	list := Plans(page)
152	if len(list) == 0 {
153		b.WriteString("No plans on this page.\n")
154		return b.String()
155	}
156	b.WriteString("| Plan | Price | Creator | Payments this / last period | All payments |\n|---|---|---|---|---|\n")
157	for _, p := range list {
158		b.WriteString("| [#" + utoa(p.ID) + " " + escCell(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ") | " + price(p.Amount, p.Period) +
159			" | [" + short(p.Payee) + "](" + link("payee/"+p.Payee.String()) + ") | " + infoPayingCell(p) +
160			" | " + itoa(p.Pulls) + " |\n")
161	}
162	b.WriteString(pager("plans", page, len(list) == PageSize))
163	return b.String()
164}
165
166func renderPlan(id uint64, from int) string {
167	p := planOf(id)
168	if p == nil {
169		return renderNotFound()
170	}
171	now := time.Now().Unix()
172	pe := payeeOf(p.Payee)
173	var b strings.Builder
174	b.WriteString("# Plan #" + utoa(p.ID) + ": " + esc(p.Title) + "\n\n")
175	b.WriteString("**" + price(p.Amount, p.Period) + "** to [" + p.Payee.String() + "](" + link("payee/"+p.Payee.String()) + ")")
176	if p.Period < 86400 {
177		b.WriteString(" (a test plan: the period is under a day)")
178	}
179	b.WriteString("\n\n")
180	b.WriteString("Plan " + utoa(p.ID) + " · published " + formatTime(p.CreatedAt) + " · " + payingText(p, now) + " · " +
181		plural(int(p.Pulls), "payment", "payments") + ", " + formatUgnot(p.Pulls*p.Amount) + " in total · last payment: " + formatTimeOrNever(p.LastPullAt) + "\n\n")
182	b.WriteString("Plans never change. New terms are published as a new plan.\n\n")
183
184	b.WriteString("## Supporters\n\n")
185	list, next := payingFrom(p, from, now)
186	if len(list) == 0 {
187		b.WriteString("No paying supporters")
188		if next >= 0 {
189			b.WriteString(" in this part of the list")
190		}
191		b.WriteString(".\n\n")
192	} else {
193		b.WriteString("| Supporter | Since | Payments | Last payment |\n|---|---|---|---|\n")
194		for _, m := range list {
195			b.WriteString("| [" + short(m.Payer) + "](" + link("payer/"+m.Payer.String()) + ") | " + formatTime(m.CreatedAt) + " | " + itoa(m.Pulls) +
196				" | " + formatTimeOrNever(m.lastPullAt()) + " |\n")
197		}
198		b.WriteString("\n")
199	}
200	if next >= 0 {
201		b.WriteString("[More supporters](" + link("plan/"+utoa(id)) + "?from=" + strconv.Itoa(next) + ")\n\n")
202	}
203	unpaid, exact := countUnpaid(p, now)
204	b.WriteString("Supporters are listed and counted from their first payment on, newest first, while their mandate is active. ")
205	b.WriteString("Cancelled and expired mandates are not listed or counted; a supporter who revoked the session on chain stays listed until the mandate is cancelled or expires. ")
206	b.WriteString(plural(unpaid, "active mandate has", "active mandates have") + " not paid yet (not listed)")
207	if !exact {
208		b.WriteString(", among the latest " + strconv.Itoa(ScanLimit))
209	}
210	b.WriteString(".\n\n")
211
212	b.WriteString("## Support this plan\n\n")
213	spend := p.Amount + FeeAllowance
214	expires := now + 365*86400
215	if pe == nil || pe.CollectorKey == "" {
216		b.WriteString("The creator has not published a collector key yet, so there is nothing to subscribe to. Ask them to run `SetCollectorKey`.\n\n")
217		return b.String()
218	}
219	if collectorFunded(pe.CollectorAddr) {
220		b.WriteString("**New supporters cannot join right now.** The creator's collector key (`" + pe.CollectorAddr.String() + "`) has received coins, so its address is an account, and the chain refuses a session for a key whose address is an account. " +
221			"This creator must publish a new collector key before new supporters can join. Existing mandates keep working until they expire; renewing needs the new key. " +
222			"A creator can also hand you a fresh session key privately: `Subscribe` accepts any session key, not only the published one.\n\n")
223		return b.String()
224	}
225	b.WriteString("You need [gnokey](https://docs.gno.land) and a key with some GNOT on " + ChainID + ". Replace `YOUR_KEY` with your key's name. " +
226		"You can support one plan of each creator at a time: every plan of a creator is collected by the same key, and the chain allows one session per key. To switch plans, cancel and revoke first (time you paid for carries over to the same plan only). ")
227	b.WriteString("These two commands give the creator's collector key (`" + pe.CollectorAddr.String() + "`) the right to take **at most " +
228		formatUgnot(spend) + " every " + formatPeriod(p.Period) + "** (the price plus a fee allowance), through this realm only, for one year.\n\n")
229	b.WriteString("1. Create the session (your own key; it cannot be done with a session). If the chain answers `session key address collides with existing account`, this collector key can no longer be used for new sessions: ask the creator to publish a new one.\n\n")
230	b.WriteString("```\ngnokey maketx session create -pubkey " + pe.CollectorKey + " -allow-paths vm/exec:" + realmPath +
231		" -spend-limit " + itoa(spend) + "ugnot -spend-period " + itoa(p.Period) + " -expires-at " + itoa(expires) + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
232	b.WriteString("2. Record the terms here:\n\n")
233	b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Subscribe -args " + utoa(p.ID) + " -args " + pe.CollectorAddr.String() +
234		" -args " + itoa(expires) + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
235	b.WriteString("The first payment is collected right after, then one every " + formatPeriod(p.Period) + ". If you paid for this plan before and that period has not ended " +
236		"(you cancelled, the creator cancelled, or your mandate expired), the new mandate's first payment waits until it ends, so time you paid for is not charged twice. " +
237		"The one exception: a wallet keeps paid time for at most " + strconv.Itoa(MaxCreditsPerPayer) + " plans it has left; beyond that, a creator's cancel keeps nothing for that creator's plan, and your own cancel or expiry lets the period that ends soonest go. Your page at `" + link("payer/<your address>") +
238		"` shows how to stop.\n")
239	return b.String()
240}
241
242func renderPayer(payer address, page int) string {
243	var b strings.Builder
244	b.WriteString("# Mandates of " + payer.String() + "\n\n")
245	b.WriteString("Each mandate lets one creator's collector key pull a fixed amount once per period. To stop one completely, run both commands shown under it: ")
246	b.WriteString("**revoke** removes the session on chain (no pull can be signed any more) and **cancel** ends the mandate here. Revoke alone already stops every payment.\n\n")
247	list := MandatesOf(payer, page)
248	if len(list) == 0 {
249		b.WriteString("No mandates on this page.\n")
250		return b.String()
251	}
252	now := time.Now().Unix()
253	for _, m := range list {
254		p := planOf(m.PlanID)
255		b.WriteString("## Mandate " + utoa(m.ID) + ": [plan #" + utoa(p.ID) + " " + esc(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ")\n\n")
256		b.WriteString("- Status here: **" + m.Status + "**")
257		if m.Status == "active" {
258			b.WriteString(" (if you revoked the session on chain, no payment can be taken)")
259		}
260		b.WriteString("\n- Price: " + price(m.Amount, m.Period) + " to [" + short(m.Payee) + "](" + link("payee/"+m.Payee.String()) + ")\n")
261		b.WriteString("- Session key: `" + m.Session.String() + "`\n")
262		b.WriteString("- Payments: " + itoa(m.Pulls) + ", " + formatUgnot(m.Paid) + " in total, last: " + formatTimeOrNever(m.LastPullAt) + "\n")
263		if m.Status == "active" {
264			if m.Pulls == 0 && m.PaidThrough > 0 {
265				b.WriteString("- First payment on " + formatTime(m.NextPullAt) + ": your current period is already paid (time carried over from your earlier mandate for this plan) · ends: " + formatTime(m.ExpiresAt) + "\n")
266			} else {
267				b.WriteString("- Next payment allowed from: " + formatTime(m.NextPullAt) + " · ends: " + formatTime(m.ExpiresAt) + "\n")
268			}
269		} else if m.PaidThrough > now {
270			if PaidThrough(payer, m.PlanID) >= m.PaidThrough {
271				b.WriteString("- Paid through " + formatTime(m.PaidThrough) + ": that time stays yours. A new mandate for this plan starts its payments then.\n")
272			} else {
273				b.WriteString("- Paid through " + formatTime(m.PaidThrough) + ", but that time could not be kept: a wallet keeps paid time for at most " +
274					strconv.Itoa(MaxCreditsPerPayer) + " plans it has left, and a creator's cancel never pushes another one out. A new mandate for this plan would pay at once.\n")
275			}
276		}
277		b.WriteString("\n")
278		if m.Status != "cancelled" {
279			b.WriteString("Revoke the session (your own key):\n\n")
280			if m.SessionPubKey != "" {
281				b.WriteString("```\ngnokey maketx session revoke -pubkey " + m.SessionPubKey + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
282			} else {
283				b.WriteString("This session's public key is not recorded here. List your sessions to find it, then run `gnokey maketx session revoke -pubkey <its gpub1 key> ... YOUR_KEY`:\n\n")
284				b.WriteString("```\ngnokey query auth/accounts/" + payer.String() + "/sessions -remote " + Remote + "\n```\n\n")
285			}
286			b.WriteString("Cancel the mandate (your own key):\n\n")
287			b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Cancel -args " + payer.String() + " -args " + m.Session.String() + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
288		}
289	}
290	b.WriteString(pager("payer/"+payer.String(), page, len(list) == PageSize))
291	return b.String()
292}
293
294func renderPayee(payee address, page int) string {
295	var b strings.Builder
296	b.WriteString("# Creator " + payee.String() + "\n\n")
297	pe := payeeOf(payee)
298	if pe == nil {
299		b.WriteString("No plans from this address.\n")
300		return b.String()
301	}
302	b.WriteString("| Plans | Payments | Received | Last payment |\n|---|---|---|---|\n")
303	b.WriteString("| " + strconv.Itoa(pe.Plans) + " | " + itoa(pe.Pulls) + " | " + formatUgnot(pe.Paid) + " | " + formatTimeOrNever(pe.LastPullAt) + " |\n\n")
304	if pe.CollectorKey == "" {
305		b.WriteString("Collector key: **not published**. Supporters cannot subscribe until it is (see [help](" + link("help") + ")).\n\n")
306	} else {
307		b.WriteString("Collector key: `" + pe.CollectorAddr.String() + "` (`" + pe.CollectorKey + "`)\n\n")
308		if collectorFunded(pe.CollectorAddr) {
309			b.WriteString("**This collector key's address has received coins, so the chain refuses new sessions for it: nobody new can subscribe.** The creator must publish a new collector key; existing mandates keep being collected with this one until they expire, and renewing needs the new key.\n\n")
310		}
311	}
312	b.WriteString("## Plans\n\n")
313	list := PlansOf(payee, page)
314	if len(list) == 0 {
315		b.WriteString("No plans on this page.\n")
316		return b.String()
317	}
318	b.WriteString("| Plan | Price | Payments this / last period | All payments | Last payment |\n|---|---|---|---|---|\n")
319	for _, p := range list {
320		b.WriteString("| [#" + utoa(p.ID) + " " + escCell(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ") | " + price(p.Amount, p.Period) + " | " +
321			infoPayingCell(p) + " | " + itoa(p.Pulls) + " | " + formatTimeOrNever(p.LastPullAt) + " |\n")
322	}
323	b.WriteString(pager("payee/"+payee.String(), page, len(list) == PageSize))
324	return b.String()
325}
326
327func renderHelp() string {
328	var b strings.Builder
329	b.WriteString("# How to use Mandate\n\n")
330	b.WriteString("Every command is for the **" + ChainID + "** test network and uses test GNOT. Replace the words in capitals. ")
331	b.WriteString("Amounts are in ugnot (1 GNOT = 1,000,000 ugnot); periods and times are in seconds and unix seconds.\n\n")
332
333	b.WriteString("## For creators\n\n")
334	b.WriteString("1. Publish a plan with your own key: a title (one line, at most " + strconv.Itoa(MaxTitleLen) + " characters, no invisible formatting characters: direction controls and zero-width characters, the joiner included, are refused, so emoji joined into one, such as families, cannot be used), the amount (at least " +
335		formatUgnot(MinAmount) + ") and the period (" + itoa(MinPeriod) + " seconds to " + itoa(MaxPeriod/86400) + " days). Plans cannot be changed.\n\n")
336	b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Offer -args \"TITLE\" -args 1000000 -args 604800 " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
337	b.WriteString("2. Make a separate key for collecting (`gnokey add COLLECTOR_KEY`) and publish its public key (the `gpub1...` value `gnokey list` shows), signed with your own key. " +
338		"**Never send coins to the collector key's address**, not even for fees (the supporter pays every fee): an address that has received coins is an account, and the chain refuses to create a session for it, so nobody new could subscribe. " +
339		"Anyone can do this to a published key with a 1 ugnot send, and a realm can even make the address an account that holds nothing. In most cases the plan page then says so; in every case supporters get the chain error `session key address collides with existing account` when they create the session, and the collector script warns. " +
340		"Then the key can no longer be used for new sessions: make a new key and publish it (this command again). New supporters then use the new key, and existing mandates keep being collected with the old one: run one collector per key. " +
341		"`Subscribe` accepts any session key you hand out, so you can also give supporters a fresh key privately:\n\n")
342	b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func SetCollectorKey -args GPUB_OF_COLLECTOR_KEY " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
343	b.WriteString("3. Collect each payment when it is due, signed with the collector key on behalf of the supporter. Only the exact price is accepted, at most once per period. The fee counts against the supporter's fee allowance, so keep it small. " +
344		"The command below uses today's minimum fee on " + ChainID + " (1 ugnot per 1,000 gas); when the chain raises its gas price, raise `-gas-fee` with it (`gnokey query auth/gasprice`), within the allowance. The collector script does this itself:\n\n")
345	b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Pull -send AMOUNTugnot -master SUPPORTER_ADDRESS " + pullGas + " " + netFlags() + " COLLECTOR_KEY\n```\n\n")
346	b.WriteString("The repository has a collector script that finds what is due through free queries and pulls it.\n\n")
347
348	b.WriteString("## For supporters\n\n")
349	b.WriteString("Open a plan's page: it shows the two exact commands, with the creator's collector key, the spend limit (price plus " + formatUgnot(FeeAllowance) +
350		" for fees) and the period filled in. The general form:\n\n")
351	b.WriteString("```\ngnokey maketx session create -pubkey COLLECTOR_GPUB -allow-paths vm/exec:" + realmPath + " -spend-limit PRICE_PLUS_" + itoa(FeeAllowance) +
352		"ugnot -spend-period PERIOD_SECONDS -expires-at UNIX_TIME " + callGas + " " + netFlags() + " YOUR_KEY\n")
353	b.WriteString("gnokey maketx call -pkgpath " + realmPath + " -func Subscribe -args PLAN_ID -args COLLECTOR_ADDRESS -args UNIX_TIME " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
354	b.WriteString("Use the same UNIX_TIME for both, at most " + itoa(MaxTerm/86400) + " days ahead. The session must allow exactly `vm/exec:" + realmPath +
355		"` and nothing else, or Pull refuses it. PERIOD_SECONDS is the plan's period, at most " + itoa(MaxPeriod/86400) + " days (the chain's limit on a spend period). " +
356		"You can support one plan of each creator at a time: all of a creator's plans are collected by one key, and the chain allows one session per key.\n\n")
357	b.WriteString("### Stop a mandate\n\n")
358	b.WriteString("Do both, with your own key. Your page (`" + link("payer/YOUR_ADDRESS") + "`) shows them filled in.\n\n")
359	b.WriteString("```\ngnokey maketx session revoke -pubkey COLLECTOR_GPUB " + callGas + " " + netFlags() + " YOUR_KEY\n")
360	b.WriteString("gnokey maketx call -pkgpath " + realmPath + " -func Cancel -args YOUR_ADDRESS -args COLLECTOR_ADDRESS " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
361
362	b.WriteString("## Checking a supporter (free)\n\n")
363	b.WriteString("To decide whether to deliver something to a supporter, ask how long their latest payment covers them: `PaidThrough` returns a unix time (0 if they never paid); deliver while now is before it. Paid time stays the supporter's after a cancel or an expiry. ")
364	b.WriteString("Do not rely on a mandate merely existing: anyone can record one without paying. A realm cannot see a session revoked on chain either, but a revoked supporter stops paying, so `PaidThrough` stops moving and runs out within one period. It runs out at the due time and moves on only when the creator's collector takes the next payment, so allow a grace equal to how often the collector runs (an hour, say) before treating someone as lapsed. The second query shows the chain's view of the session.\n\n")
365	b.WriteString("```\ngnokey query vm/qeval -data '" + realmPath + ".PaidThrough(address(\"PAYER\"), PLAN_ID)' -remote " + Remote + "\n")
366	b.WriteString("gnokey query auth/accounts/PAYER/session/COLLECTOR_ADDRESS -remote " + Remote + "\n```\n\n")
367
368	b.WriteString("## Rules the realm enforces\n\n")
369	b.WriteString("- Pull: signed with a session key as a direct call; the session allows exactly this realm; a recorded, active mandate for that payer and key; exactly the price in ugnot; at most once per period (the next one is due one period after the last); not after the expiry.\n")
370	b.WriteString("- Every other function refuses session keys and coins.\n")
371	b.WriteString("- The first payment can be pulled as soon as the mandate is recorded (billing in advance). A missed period is never collected later.\n")
372	b.WriteString("- A wallet can have at most " + strconv.Itoa(MaxSessionsPerWallet) + " sessions, so at most " + strconv.Itoa(MaxSessionsPerWallet) + " mandates at a time.\n")
373	return b.String()
374}
375
376func renderNotFound() string {
377	return "# Not found\n\nThere is no such page. [Back to Mandate](" + link("") + ")\n"
378}
379
380// payingText is the plan headline's count of payments per period. It
381// counts payments, not distinct people: a creator paying its own plan from
382// a second wallet counts too.
383func payingText(p *Plan, now int64) string {
384	current, previous := p.paidWindows(now)
385	start := now / p.Period * p.Period
386	return plural(current, "payment", "payments") + " in the current period (since " + formatTime(start) + "), " +
387		strconv.Itoa(previous) + " in the one before"
388}
389
390// payingCell is the count in tables: paid this period / the one before.
391func payingCell(p *Plan, now int64) string {
392	current, previous := p.paidWindows(now)
393	return strconv.Itoa(current) + " / " + strconv.Itoa(previous)
394}
395
396func infoPayingCell(p PlanInfo) string {
397	return strconv.Itoa(p.PaidThisPeriod) + " / " + strconv.Itoa(p.PaidLastPeriod)
398}
399
400// intParam returns the integer value of key in the query, or def.
401func intParam(query, key string, def int) int {
402	for _, kv := range strings.Split(query, "&") {
403		if strings.HasPrefix(kv, key+"=") {
404			n, err := strconv.Atoi(kv[len(key)+1:])
405			if err == nil && n >= 0 && n <= 1_000_000_000 {
406				return n
407			}
408		}
409	}
410	return def
411}
412
413// link returns the gnoweb link to a page of this realm.
414func link(page string) string {
415	p := strings.TrimPrefix(realmPath, "gno.land")
416	if page == "" {
417		return p
418	}
419	return p + ":" + page
420}
421
422func pager(page string, n int, more bool) string {
423	s := ""
424	if n > 1 {
425		s += "[Previous page](" + link(page) + "?page=" + strconv.Itoa(n-1) + ") "
426	}
427	if more {
428		s += "[Next page](" + link(page) + "?page=" + strconv.Itoa(n+1) + ")"
429	}
430	if s == "" {
431		return ""
432	}
433	return s + "\n\n"
434}
435
436func pageParam(query string) int {
437	for _, kv := range strings.Split(query, "&") {
438		if strings.HasPrefix(kv, "page=") {
439			n, err := strconv.Atoi(kv[5:])
440			if err == nil && n >= 1 && n <= 1_000_000 {
441				return n
442			}
443		}
444	}
445	return 1
446}
447
448func plural(n int, one, many string) string {
449	if n == 1 {
450		return "1 " + one
451	}
452	return strconv.Itoa(n) + " " + many
453}
454
455func netFlags() string {
456	return "-broadcast -chainid " + ChainID + " -remote " + Remote
457}
458
459func price(amount, period int64) string {
460	return formatUgnot(amount) + " every " + formatPeriod(period)
461}
462
463// formatUgnot shows an amount in GNOT with up to six decimals.
464func formatUgnot(n int64) string {
465	whole := n / 1_000_000
466	frac := n % 1_000_000
467	s := itoa(whole)
468	if frac != 0 {
469		f := strconv.FormatInt(frac+1_000_000, 10)[1:]
470		s += "." + strings.TrimRight(f, "0")
471	}
472	return s + " GNOT"
473}
474
475// formatPeriod shows a number of seconds in the largest exact unit.
476func formatPeriod(sec int64) string {
477	unit := func(n int64, one, many string) string {
478		if n == 1 {
479			return one
480		}
481		return itoa(n) + " " + many
482	}
483	switch {
484	case sec%604800 == 0:
485		return unit(sec/604800, "week", "weeks")
486	case sec%86400 == 0:
487		return unit(sec/86400, "day", "days")
488	case sec%3600 == 0:
489		return unit(sec/3600, "hour", "hours")
490	case sec%60 == 0:
491		return unit(sec/60, "minute", "minutes")
492	}
493	return unit(sec, "second", "seconds")
494}
495
496func formatTime(unix int64) string {
497	return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04 UTC")
498}
499
500func formatTimeOrNever(unix int64) string {
501	if unix == 0 {
502		return "never"
503	}
504	return formatTime(unix)
505}
506
507func short(a address) string {
508	s := a.String()
509	if len(s) < 14 {
510		return s
511	}
512	return s[:8] + "…" + s[len(s)-4:]
513}