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

bounded_test.gno

package vouch

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
)

// Finding 325-cost-at-caps-1. Anyone can add a vouch edge to somebody else's
// page, with a zero bond, and nothing sweeps them. Both tables on an address
// page rendered every edge, so the cost every reader of that page paid was set
// by whoever had been most persistent.
//
// The loop is inline rather than in a helper on purpose: testing.SetRealm is
// call-frame scoped, so switching account inside a helper leaves the crossing
// call running as whoever the test body was, and every iteration records the
// same edge. The first version of this test did exactly that, recorded one
// voucher instead of two hundred, and still passed.
func TestAnAddressPageIsBoundedByWhatItShows(cur realm, t *testing.T) {
	reset()

	for i := 0; i < 40; i++ {
		fund(0)
		testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("v" + strconv.Itoa(i))))
		Vouch(cross(cur), alice, "because "+strconv.Itoa(i))
	}
	small := Render("addr/" + alice.String())

	for i := 40; i < 200; i++ {
		fund(0)
		testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("v" + strconv.Itoa(i))))
		Vouch(cross(cur), alice, "because "+strconv.Itoa(i))
	}
	big := Render("addr/" + alice.String())

	if n := len(VouchedBy(alice)); n != 200 {
		t.Fatalf("only %d voucher(s) were recorded, so this test is measuring nothing", n)
	}

	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 address page grew from %d rows to %d when the vouchers went from 40 to 200: "+
			"anybody can set what every reader of this page pays", rowsSmall, rowsBig)
	}
}

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/vouch/v0"
gno = "0.9"

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914348
  max_deposit = "14000000ugnot"

render.gno

package vouch

import (
	"strconv"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/num/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
	vo "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/vouch/v0"
)

// IndexEdges is how many vouch edges one address's page lists in each
// direction.
//
// Finding 325-cost-at-caps-1: both tables rendered every edge. Anyone can add
// an edge to somebody else's page, with a zero bond, and nothing sweeps them,
// so the cost every reader of that page pays was set by whoever had been most
// persistent.
const IndexEdges = 20

// Render routes two views: the realm's own index, and one address's page.
//
// An address carries no slash, so the per-address route is a path element and
// not a prefix strip.
func Render(path string) string {
	req := realmpath.Parse(path)

	switch req.PathPart(0) {
	case "":
		return renderIndex()
	case "addr":
		return renderAddr(req.PathPart(1))
	default:
		return md.H1("Not found") + "No such view: " + ui.Inline(req.Path)
	}
}

func renderIndex() string {
	out := md.H1("Vouch")
	out += "A web of trust other realms gate on. One address vouches for another, " +
		"in writing, optionally with GNOT locked behind it.\n\n"

	t := ui.NewTable("vouches", "people vouched for", "bonded", "awaiting withdrawal")
	t.Row(
		strconv.Itoa(graph.Count()),
		strconv.Itoa(graph.People()),
		num.GNOTf(graph.TotalBonded()),
		num.GNOTf(graph.TotalOwed()),
	)
	out += t.String()

	out += md.H2("Most vouched for")
	out += board()

	out += md.H2("The gate")
	out += "One line in the realm that wants it, and it costs no transaction:\n\n"
	out += md.LanguageCodeBlock("go", `import "`+realmPath+`"

if !vouch.IsTrusted(addr, 2) {
	panic("get two people to vouch for you first")
}`)
	out += md.Italic("A score counts distinct vouchers, so restating a vouch does not " +
		"raise it and revoking lowers it. It does not count distinct people: a pair " +
		"vouching for each other both reach one, which is why a real gate asks for " +
		"more.") + "\n\n"

	out += md.H2("Take part")
	out += ui.Action("\U0001F91D Vouch", "Vouch", "target", "", "reason", "") +
		" · " + ui.Action("\U0001F4B0 Withdraw a refunded bond", "Withdraw") + "\n\n"
	out += md.Italic("Coins sent with Vouch are locked as a bond on that vouch and come " +
		"back when you revoke it. There is no slashing: deciding that a vouch was a lie " +
		"needs an arbiter, and choosing one is the whole design question.") + "\n"

	return out
}

func board() string {
	rows := graph.Leaderboard(BoardSize)
	if len(rows) == 0 {
		return ui.Empty("Nobody has been vouched for yet.")
	}
	t := ui.NewTable("", "address", "vouchers", "bonded")
	for i, r := range rows {
		t.Row(
			ui.Podium(i),
			md.Link(ui.AddrText(r.Addr), vo.AddrURL(realmPath, r.Addr)),
			strconv.Itoa(r.Score),
			num.GNOTf(r.Bonded),
		)
	}
	return t.String()
}

func renderAddr(raw string) string {
	addr := address(raw)
	if !addr.IsValid() {
		return md.H1("Vouch") + "Not an address: " + ui.Inline(raw)
	}

	out := md.H1("Vouch for " + ui.AddrText(addr))
	out += ui.AddrFull(addr) + "\n\n"

	score := graph.ScoreOf(addr)
	t := ui.NewTable("vouchers", "bonded on them", "trusted at 2", "awaiting withdrawal")
	t.Row(
		strconv.Itoa(score),
		num.GNOTf(graph.BondedFor(addr)),
		yesno(graph.IsTrusted(addr, 2)),
		num.GNOTf(graph.Owed(addr)),
	)
	out += t.String()

	out += md.H2("Vouched for by")
	out += inbound(addr)

	out += md.H2("Vouches for")
	out += outbound(addr)

	out += "\n" + ui.Action("\U0001F91D Vouch for this address", "Vouch",
		"target", addr.String(), "reason", "") +
		" · " + ui.Action("\U0000274C Revoke mine", "Revoke", "target", addr.String()) + "\n"
	return out
}

func inbound(addr address) string {
	from := graph.VouchedBy(addr)
	if len(from) == 0 {
		return ui.Empty("Nobody vouches for this address.")
	}
	shown := from
	if len(shown) > IndexEdges {
		shown = shown[len(shown)-IndexEdges:]
	}
	t := ui.NewTable("voucher", "reason", "bond", "mutual", "since")
	for _, f := range shown {
		v, ok := graph.Get(f, addr)
		if !ok {
			continue
		}
		t.Row(
			md.Link(ui.AddrText(f), vo.AddrURL(realmPath, f)),
			ui.Cell(v.Reason),
			num.GNOTf(v.Bond),
			yesno(graph.Mutual(f, addr)),
			strconv.FormatInt(v.At, 10),
		)
	}
	out := t.String()
	if len(from) > IndexEdges {
		out += md.Italic("Showing "+strconv.Itoa(IndexEdges)+" of "+
			strconv.Itoa(len(from))+" vouchers.") + "\n"
	}
	return out
}

func outbound(addr address) string {
	to := graph.VouchesOf(addr)
	if len(to) == 0 {
		return ui.Empty("This address vouches for nobody.")
	}
	shownTo := to
	if len(shownTo) > IndexEdges {
		shownTo = shownTo[len(shownTo)-IndexEdges:]
	}
	t := ui.NewTable("for", "reason", "bond", "their vouchers")
	for _, target := range shownTo {
		v, ok := graph.Get(addr, target)
		if !ok {
			continue
		}
		t.Row(
			md.Link(ui.AddrText(target), vo.AddrURL(realmPath, target)),
			ui.Cell(v.Reason),
			num.GNOTf(v.Bond),
			strconv.Itoa(graph.ScoreOf(target)),
		)
	}
	out := t.String()
	if len(to) > IndexEdges {
		out += md.Italic("Showing "+strconv.Itoa(IndexEdges)+" of "+
			strconv.Itoa(len(to))+" vouches.") + "\n"
	}
	return out
}

func yesno(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

vouch.gno

// Package vouch is a web of trust other realms can gate on: one address
// vouches for another, in writing, optionally with GNOT locked behind it.
//
// The one call that matters is a plain read:
//
//	import "gno.land/r/moul/x/social/vouch/v0"
//
//	func Claim(cur realm) {
//		if !vouch.IsTrusted(cur.Previous().Address(), 2) {
//			panic("get two people to vouch for you first")
//		}
//		…
//	}
//
// [IsTrusted] takes no cur realm on purpose. A read with no realm token is
// borrowed: gno opens no realm frame for it, so it costs the caller nothing
// beyond the read and cannot be tricked into acting as anybody. Nothing here
// branches on who is asking, and no read in this realm ever will: the answer
// to "is this address trusted" must not depend on who wants to know.
//
// # What it does, and what it refuses to do
//
// [Vouch] is payable. Any coins sent with it are locked as a bond on that
// vouch, which is the voucher putting their own money where their claim is. A
// bond is optional and zero is the ordinary case. [Revoke] takes the vouch
// back and credits the bond to the voucher, who collects it with [Withdraw].
//
// There is no slashing in v0 and that is the interesting half. Slashing needs
// an arbiter, somebody who decides a vouch was a lie, and every candidate is
// a design question rather than a feature: a DAO vote is a popularity contest,
// a challenge market pays whoever is loudest, an oracle is one key that can
// confiscate anybody's money. The bond is still worth having without it,
// because an illiquid deposit is a cost a hundred throwaway addresses cannot
// all pay at once.
//
// # No token
//
// This realm issues none, deliberately. A transferable vouch is a bought
// reputation, and the moment a vouch can be sold the score stops measuring
// what it says it measures. The bond is GNOT: value at risk, without being a
// market in trust itself. The README says what would change the answer.
package vouch

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"strconv"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/envelope/v0"
	vo "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/vouch/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 every
// read this realm exports is borrowed and would report whichever realm called
// it, building every link against somebody else's page.
const realmPath = "gno.land/r/moul/x/social/vouch/v0"

// denom is the only coin a bond can be posted in.
const denom = "ugnot"

// BoardSize is how many addresses the index page ranks.
const BoardSize = 10

// graph holds every vouch and the refund ledger. A redeploy would wipe it
// while leaving the bonded coins at this address, which is why this realm is
// not private (see gnomod.toml).
var graph = vo.NewGraph()

// Vouch records that the caller stands behind target, for the stated reason.
//
// It is payable: coins sent with the call are locked as a bond on this vouch
// and are returned by [Revoke], never by anything else. Sending nothing is
// fine and is the ordinary case.
//
// Vouching again for the same address UPDATES the reason and ADDS to the
// bond. It does not count twice: the score this realm exists to publish is a
// count of people, so a second transaction from the same address buys
// precisely nothing. Vouching for yourself is refused.
func Vouch(cur realm, target address, reason string) {
	who, userCall := caller(cur)
	bond := bondOf(userCall)

	updated, err := graph.Record(who, target, reason, bond, runtime.ChainHeight())
	if err != nil {
		panic(err.Error())
	}
	event := "Vouch"
	if updated {
		event = "Revouch"
	}
	chain.Emit(event, "from", who.String(), "for", target.String(),
		"bond", strconv.FormatInt(bond, 10))
}

// Revoke withdraws the caller's vouch for target and credits any bond back to
// them. The coins do not move here: call [Withdraw] to collect them.
//
// Splitting it in two is the pull-payment pattern. A realm that sent on revoke
// would be handing control to the recipient in the middle of its own state
// change, and a recipient that refuses the coins could make revoking
// impossible.
func Revoke(cur realm, target address) int64 {
	who, _ := caller(cur)
	refund, err := graph.Revoke(who, target)
	if err != nil {
		panic(err.Error())
	}
	chain.Emit("Revoke", "from", who.String(), "for", target.String(),
		"refund", strconv.FormatInt(refund, 10))
	return refund
}

// Withdraw pays the caller every bond their revoked vouches freed, and
// returns the amount sent.
//
// The credit is zeroed before the coins leave, so a recipient that calls
// straight back in finds nothing to take.
func Withdraw(cur realm) int64 {
	who, _ := caller(cur)
	amount, err := graph.Withdraw(who)
	if err != nil {
		panic(err.Error())
	}
	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bnk.SendCoins(cur.Address(), who, chain.NewCoins(chain.NewCoin(denom, amount)))
	chain.Emit("Withdraw", "to", who.String(), "amount", strconv.FormatInt(amount, 10))
	return amount
}

// IsTrusted reports whether addr is vouched for by at least min distinct
// addresses. This is the gate, and it is one line at the call site.
//
// A min below one is read as one: a gate that lets everybody through is a bug
// in the caller rather than an answer this realm will agree to.
//
// It cannot tell you that the vouchers are distinct people. Two addresses
// vouching for each other both reach a score of one, which [Mutual] exposes
// and which is the reason to ask for more than one.
func IsTrusted(addr address, min int) bool { return graph.IsTrusted(addr, min) }

// ScoreOf is how many distinct addresses vouch for addr.
func ScoreOf(addr address) int { return graph.ScoreOf(addr) }

// BondedFor is the total ugnot locked on addr by everyone vouching for them.
func BondedFor(addr address) int64 { return graph.BondedFor(addr) }

// VouchedBy is every address that vouches for addr, sorted.
func VouchedBy(addr address) []address { return graph.VouchedBy(addr) }

// VouchesOf is every address addr vouches for, sorted.
func VouchesOf(addr address) []address { return graph.VouchesOf(addr) }

// Mutual reports whether a and b vouch for each other, which is the cheapest
// sybil shape and therefore worth discounting.
func Mutual(a, b address) bool { return graph.Mutual(a, b) }

// ReasonFrom is what from wrote about target, or the empty string. It is raw
// caller text: escape it before rendering it anywhere.
func ReasonFrom(from, target address) string { return graph.ReasonFrom(from, target) }

// BondFrom is what from locked on target, or zero.
func BondFrom(from, target address) int64 { return graph.BondFrom(from, target) }

// Count is how many vouches exist.
func Count() int { return graph.Count() }

// People is how many addresses have at least one vouch for them.
func People() int { return graph.People() }

// Owed is what addr can collect with [Withdraw].
func Owed(addr address) int64 { return graph.Owed(addr) }

// TotalBonded is everything locked on vouches that still stand.
func TotalBonded() int64 { return graph.TotalBonded() }

// TotalOwed is every revoked bond nobody has collected yet. This realm holds
// TotalBonded plus TotalOwed on behalf of other people.
func TotalOwed() int64 { return graph.TotalOwed() }

// Badge is the one-line trust mark for addr, for a host realm that wants to
// show what its gate just read. Like [IsTrusted] it is a borrowed read and
// takes no realm token.
func Badge(addr address) string {
	return vo.Badge(realmPath, addr, graph.ScoreOf(addr), graph.BondedFor(addr))
}

// bondOf reads the coins attached to this call, and only when the chain
// credited them to THIS realm.
//
// The envelope is the transaction's, not the frame's: a realm that was itself
// paid and then calls here would report coins sitting at its own address, and
// crediting them would let it bond money this realm never received. A realm
// may vouch, with no bond; a realm may not vouch while holding somebody's
// payment, and saying so loudly beats silently reading the bond as zero.
//
// It takes the answer rather than the frame because a realm argument in this
// package must be named cur, which would make this a crossing function.
func bondOf(userCall bool) int64 {
	if userCall {
		return envelope.Amount(denom)
	}
	if !envelope.IsEmpty() {
		panic("a realm cannot forward a bond: those coins were credited to the realm the user paid, not to this one")
	}
	return 0
}

// caller is the address that called us, checked the one way that is safe,
// plus whether it reached us as a direct user transaction.
//
// Both come from here so the realm reads cur.Previous() in exactly one place,
// the one guarded by cur.IsCurrent().
func caller(cur realm) (who address, userCall bool) {
	if !cur.IsCurrent() {
		panic("spoofed realm: cur is not the live crossing frame")
	}
	prev := cur.Previous()
	return prev.Address(), prev.IsUserCall()
}

vouch_test.gno

package vouch

import (
	"strings"
	"testing"

	"chain"
	"chain/banker"

	vo "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/vouch/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

var (
	alice = testutils.TestAddress("alice")
	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
// every test that reads a score, a bond or a refund starts here.
func reset() { graph = vo.NewGraph() }

// fund simulates the coins attached to the next call: the runtime credits the
// realm's address first, and the crossing function then reads the envelope off
// the transaction. fund(0) clears it, which is the ordinary unbonded case.
//
// testing.SetRealm is call-frame scoped, so the caller still switches account
// inline in the test body right before crossing.
func fund(amount int64) {
	if amount <= 0 {
		testing.SetOriginSend(chain.Coins{})
		return
	}
	testing.IssueCoins(realmAddr, chain.Coins{{denom, amount}})
	testing.SetOriginSend(chain.Coins{{denom, amount}})
}

func balanceOf(addr address) int64 {
	return banker.NewReadonlyBanker().GetCoins(addr).AmountOf(denom)
}

// The score counts people, which is the property every caller of IsTrusted
// depends on: a repeated vouch does not raise it, a revoke lowers it.
func TestScoreCountsPeopleAndNotVouches(cur realm, t *testing.T) {
	reset()

	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "worked with them for two years")
	uassert.Equal(t, 1, ScoreOf(alice))

	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "still true")
	uassert.Equal(t, 1, ScoreOf(alice), "one person is one point, however often they say it")
	uassert.Equal(t, "still true", ReasonFrom(bob, alice), "the reason was updated")
	uassert.Equal(t, 1, Count())

	fund(0)
	testing.SetRealm(testing.NewUserRealm(carol))
	Vouch(cross(cur), alice, "we shipped together")
	uassert.Equal(t, 2, ScoreOf(alice))
	uassert.Equal(t, 1, People(), "one address has been vouched for")

	fund(0)
	testing.SetRealm(testing.NewUserRealm(carol))
	Revoke(cross(cur), alice)
	uassert.Equal(t, 1, ScoreOf(alice), "revoking lowers the score")
	uassert.Equal(t, 1, Count())
}

func TestVouchRefusals(cur realm, t *testing.T) {
	reset()

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "cannot vouch for itself", func() {
		Vouch(cross(cur), alice, "I am great")
	})

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "reason is empty", func() {
		Vouch(cross(cur), bob, "   ")
	})

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "reason is empty", func() {
		Vouch(cross(cur), bob, "one line\nonly")
	})

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "no such vouch", func() {
		Revoke(cross(cur), bob)
	})

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "nothing to withdraw", func() {
		Withdraw(cross(cur))
	})

	uassert.Equal(t, 0, Count())
}

// The bond follows the vouch in both directions, and the coins only move on
// Withdraw. Balances are asserted here because the bank does not carry over
// between test functions.
func TestTheBondIsLockedUntilTheVouchIsRevoked(cur realm, t *testing.T) {
	reset()
	before := balanceOf(bob)

	fund(1_000_000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "1 GNOT says this is a real person")
	uassert.Equal(t, int64(1_000_000), BondedFor(alice))
	uassert.Equal(t, int64(1_000_000), TotalBonded())
	uassert.Equal(t, int64(0), Owed(bob), "nothing is owed while the vouch stands")

	// Vouching again adds to the bond rather than replacing it.
	fund(500_000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "doubling down")
	uassert.Equal(t, int64(1_500_000), BondedFor(alice))
	uassert.Equal(t, int64(1_500_000), BondFrom(bob, alice))

	// Revoking moves the bond to the ledger and nothing else.
	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	refund := Revoke(cross(cur), alice)
	uassert.Equal(t, int64(1_500_000), refund)
	uassert.Equal(t, int64(0), BondedFor(alice))
	uassert.Equal(t, int64(1_500_000), Owed(bob))
	uassert.Equal(t, int64(1_500_000), TotalOwed())
	uassert.Equal(t, before, balanceOf(bob), "revoking sends nothing")

	// Withdrawing is what moves the coins, once.
	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	got := Withdraw(cross(cur))
	uassert.Equal(t, int64(1_500_000), got)
	uassert.Equal(t, before+1_500_000, balanceOf(bob), "the bond came back")
	uassert.Equal(t, int64(0), Owed(bob))
	uassert.Equal(t, int64(0), TotalOwed())

	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "nothing to withdraw", func() {
		Withdraw(cross(cur))
	})
	uassert.Equal(t, before+1_500_000, balanceOf(bob), "and only once")
}

// A bond belongs to whoever posted it, not to whoever it was posted on.
func TestOnlyTheVoucherGetsTheBondBack(cur realm, t *testing.T) {
	reset()

	fund(700_000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "my money, my claim")

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "no such vouch", func() {
		Revoke(cross(cur), bob)
	})

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "nothing to withdraw", func() {
		Withdraw(cross(cur))
	})
	uassert.Equal(t, int64(700_000), BondedFor(alice), "the bond is untouched")
}

func TestIsTrustedIsTheGate(cur realm, t *testing.T) {
	reset()

	uassert.False(t, IsTrusted(alice, 1), "nobody starts trusted")
	uassert.False(t, IsTrusted(alice, 0), "a zero min does not open the gate for nobody")

	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "one")
	uassert.True(t, IsTrusted(alice, 1))
	uassert.False(t, IsTrusted(alice, 2))

	fund(0)
	testing.SetRealm(testing.NewUserRealm(carol))
	Vouch(cross(cur), alice, "two")
	uassert.True(t, IsTrusted(alice, 2))
	uassert.False(t, IsTrusted(alice, 3))

	// The cheapest sybil shape, and the reason a real gate asks for two.
	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	Vouch(cross(cur), bob, "back at you")
	uassert.True(t, Mutual(alice, bob))
	uassert.True(t, IsTrusted(bob, 1), "a mutual pair passes a gate set at one")
	uassert.False(t, IsTrusted(bob, 2))
}

func TestTheTwoDirections(cur realm, t *testing.T) {
	reset()

	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	Vouch(cross(cur), bob, "a to b")
	fund(0)
	testing.SetRealm(testing.NewUserRealm(alice))
	Vouch(cross(cur), carol, "a to c")
	fund(0)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), carol, "b to c")

	uassert.Equal(t, 2, len(VouchesOf(alice)))
	uassert.Equal(t, 0, len(VouchedBy(alice)))
	uassert.Equal(t, 2, len(VouchedBy(carol)))
	uassert.Equal(t, 0, len(VouchesOf(carol)))
	uassert.Equal(t, "b to c", ReasonFrom(bob, carol))
	uassert.Equal(t, "", ReasonFrom(carol, bob))
	uassert.Equal(t, int64(0), BondFrom(alice, bob), "an unbonded vouch is worth nothing")
}

// Badge is a borrowed read: a host realm calls it with no realm token and
// gets a line pointing back at this realm's page.
func TestBadge(cur realm, t *testing.T) {
	reset()
	uassert.True(t, strings.Contains(Badge(alice), "not vouched for"))

	fund(2_000_000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "one")

	got := Badge(alice)
	uassert.True(t, strings.Contains(got, "1 voucher]"), got)
	uassert.True(t, strings.Contains(got, "2 GNOT bonded"), got)
	uassert.True(t, strings.Contains(got, "/r/moul/x/social/vouch/v0:addr/"+alice.String()), got)
}

// 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()

	fund(3_000_000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Vouch(cross(cur), alice, "a reason with [a link](x) and a | pipe")
	fund(0)
	testing.SetRealm(testing.NewUserRealm(carol))
	Vouch(cross(cur), alice, "second voucher")

	index := Render("")
	uassert.True(t, strings.Contains(index, "| 2 | 1 | 3 GNOT | 0 GNOT |"),
		"vouches, people, bonded, owed: "+index)
	uassert.True(t, strings.Contains(index, `import "`+realmPath+`"`), "the index is the gate doc")
	uassert.True(t, strings.Contains(index, "func=Vouch"), "the index offers the transaction")
	uassert.True(t, strings.Contains(index, "\U0001F947"), "the board has a podium: "+index)

	page := Render("addr/" + alice.String())
	uassert.True(t, strings.Contains(page, alice.String()), "the page names the address")
	uassert.True(t, strings.Contains(page, "a reason with \\[a link\\]\\(x\\) and a \\| pipe"),
		"the reason is escaped where it is shown: "+page)
	uassert.True(t, strings.Contains(page, "func=Revoke"))

	// The other direction of the same edge, from the voucher's page.
	vouchers := Render("addr/" + bob.String())
	uassert.True(t, strings.Contains(vouchers, "This address vouches for nobody.") == false,
		"bob vouches for alice: "+vouchers)
	uassert.True(t, strings.Contains(vouchers, "Nobody vouches for this address."))

	uassert.Equal(t, "# Vouch\nNot an address: nope", Render("addr/nope"))
	uassert.True(t, strings.HasPrefix(Render("elsewhere"), "# Not found"))

	// An empty graph says so rather than rendering an empty table.
	reset()
	uassert.True(t, strings.Contains(Render(""), "Nobody has been vouched for yet."))
}

func TestRenderOfAnUnknownAddress(cur realm, t *testing.T) {
	reset()
	page := Render("addr/" + carol.String())
	uassert.True(t, strings.Contains(page, "Nobody vouches for this address."), page)
	uassert.True(t, strings.Contains(page, "This address vouches for nobody."), page)
	uassert.True(t, strings.Contains(page, "| 0 | 0 GNOT | no | 0 GNOT |"), page)
}