Playground
curated.gno
// Package curated is a list anyone can get onto by locking a deposit, and
// anyone can try to get somebody else off by matching that deposit with a bond.
// The loser of the challenge pays the winner.
//
// It is the registry member of a family of small social apps: a list is the
// thing every other one of them eventually needs, and a list is only worth
// reading if being on it cost something.
//
// Apply(key, url, description) -send 1000000ugnot list it, immediately
// Challenge(key) -send <the deposit> object to it
// Vote(key, keep) while the window is open
// Resolve(key) anyone, after it closes
// Unlist(key) the owner, if unchallenged
// Withdraw() collect what you won
//
// # Money in, money out
//
// Coins arrive in the envelope of a call and sit at this realm's address. They
// never leave by being pushed: a payout is a credit in a ledger and the payee
// calls [Withdraw] for their own. A realm that looped over winners and sent to
// each one would fail entirely when one of them could not be paid, and would
// hand a griefer a cheap denial of service for the price of one entry.
//
// Every ugnot here is therefore either backing a live entry or an open
// challenge, or already assigned to somebody. The realm's own tests assert
// exactly that against the chain balance.
//
// # Voting is sybil-prone, and the bonds are GNOT
//
// [Vote] is one address, one vote, unweighted, and an address is free. Read a
// resolution as "nobody with a stake objected enough", never as a verdict.
// Gating a vote on something harder to manufacture is a different problem with
// its own realm behind it, r/moul/x/social/vouch, a sibling in this family.
//
// Bonds are GNOT and not a token of this list's own: see the README on why
// that is the only answer available at v0 and what would change it.
//
// # What v0 does not do, in the order it should be fixed
//
// 1. Voters are paid nothing. Voting costs gas and returns nothing, so the
// only two addresses with a reason to vote are the ones with money on the
// outcome. A share of the loser's stake for the winning side is the
// standard answer and the first thing to add.
// 2. There is no application period: [Apply] lists immediately.
// 3. A challenge cannot be withdrawn and a vote cannot be changed.
package curated
import (
"chain"
"chain/banker"
"chain/runtime"
"strconv"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/envelope/v0"
cu "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/curated/v0"
)
// realmPath is this realm's own path, the one its gnomod.toml module line
// declares. Render builds its links from it rather than from
// unsafe.CurrentRealm(), which in a plain read reports the CALLER.
const realmPath = "gno.land/r/moul/x/social/curated/v0"
const (
// Denom is what a deposit and a bond are paid in. Native coins, so the
// amounts are real to a challenger before this list is worth anything.
Denom = "ugnot"
// Deposit is what listing costs, and therefore also what challenging one
// of today's entries costs. One GNOT: enough to make a thousand junk
// entries a real expense, cheap enough that one honest entry is not a
// decision.
Deposit = int64(1000000)
// ChallengeBlocks is how long a challenge takes to resolve. Long enough
// for a reader who is not watching the chain to notice and vote, short
// enough that an entry is not held hostage.
ChallengeBlocks = int64(1000)
)
// list is every entry and the credit ledger behind them. A redeploy would wipe
// it while leaving the coins at the address, which is what the note in
// gnomod.toml is about.
var list = cu.New(Deposit, ChallengeBlocks)
// Apply lists an entry under key, in exchange for exactly [Deposit] ugnot.
//
// The entry is on the list the moment this returns: there is no application
// period in v0, and the check on a bad entry is that anybody can challenge it.
// The deposit comes back through [Unlist] and [Withdraw] if nobody ever does.
//
// key is a slug: lowercase ASCII letters, digits, '-', '_' and '.', starting
// alphanumeric. A key whose entry was removed is free to apply for again.
func Apply(cur realm, key, url, description string) {
// Both checks are inlined rather than hidden behind caller(), and in this
// order. cur.IsCurrent() before cur.Previous() is the realm-token rule;
// IsUserCall before the envelope read is the payment one, because the
// envelope reports what the SIGNER attached to the transaction and not
// what reached this realm. Without it a realm the user called keeps the
// coins and calls in here as often as it likes, every call reading the
// same send: that is r/moul/grant Fund, which recorded 5 donations of
// 1 GNOT from one 1 GNOT send with nothing in the treasury.
if !cur.IsCurrent() {
panic("spoofed realm: cur is not the live crossing frame")
}
if !cur.Previous().IsUserCall() {
panic("curated: paying in must be a direct user transaction")
}
who := cur.Previous().Address()
paid := envelope.RequireExactly(Denom, Deposit)
if err := list.Apply(key, url, description, who, paid, runtime.ChainHeight()); err != nil {
panic(err.Error())
}
chain.Emit("Apply", "key", key, "owner", who.String(),
"deposit", strconv.FormatInt(paid, 10))
}
// Challenge objects to an entry, in exchange for a bond equal to that entry's
// own deposit, and opens a vote that closes [ChallengeBlocks] blocks later.
//
// An owner cannot challenge their own entry: it would cost them nothing and
// would make the entry immune to a real challenge for the whole window.
func Challenge(cur realm, key string) {
// The two guards every payable call needs, inlined; see Apply.
if !cur.IsCurrent() {
panic("spoofed realm: cur is not the live crossing frame")
}
if !cur.Previous().IsUserCall() {
panic("curated: paying in must be a direct user transaction")
}
who := cur.Previous().Address()
// The bond is read before the envelope is, so somebody who attaches coins
// to a challenge of something unchallengeable is told which of the two is
// wrong.
bond, ok := list.BondFor(key)
if !ok {
panic("curated: " + key + " is not an entry that can be challenged")
}
envelope.RequireExactly(Denom, bond)
if err := list.Challenge(key, who, bond, runtime.ChainHeight()); err != nil {
panic(err.Error())
}
c, _ := list.ChallengeOf(key)
chain.Emit("Challenge", "key", key, "by", who.String(),
"bond", strconv.FormatInt(bond, 10),
"deadline", strconv.FormatInt(c.Deadline, 10))
}
// Vote takes a side on an open challenge: keep the entry, or remove it.
//
// One address, one vote, unweighted, and it cannot be changed. An address is
// free, so this is cheap to manufacture; see the package doc.
func Vote(cur realm, key string, keep bool) {
who := caller(cur)
if err := list.Vote(key, who, keep, runtime.ChainHeight()); err != nil {
panic(err.Error())
}
chain.Emit("Vote", "key", key, "by", who.String(), "keep", strconv.FormatBool(keep))
}
// Resolve closes a challenge whose window has passed. Anyone may call it, so
// neither party can stall the other by sitting still.
//
// A majority of keep votes keeps the entry and credits its owner the bond.
// Otherwise the entry is removed and the challenger is credited the bond plus
// the deposit. A tie, including nobody voting at all, keeps the entry: the
// incumbent is the one already at risk, so a challenge that convinced nobody
// loses, which is what makes being wrong cost something.
func Resolve(cur realm, key string) {
who := caller(cur)
out, err := list.Resolve(key, runtime.ChainHeight())
if err != nil {
panic(err.Error())
}
chain.Emit("Resolve", "key", key,
"kept", strconv.FormatBool(out.Kept),
"winner", out.Winner.String(),
"amount", strconv.FormatInt(out.Amount, 10),
"keep", strconv.FormatInt(out.Keep, 10),
"remove", strconv.FormatInt(out.Remove, 10),
"by", who.String())
}
// Unlist takes the caller's own entry off the list and credits them the
// deposit back, which [Withdraw] then pays out.
//
// It is refused while a challenge is open: an owner who could walk away
// mid-challenge would be risking nothing, which is the one thing the deposit
// exists to prevent.
func Unlist(cur realm, key string) {
who := caller(cur)
if err := list.Unlist(key, who); err != nil {
panic(err.Error())
}
chain.Emit("Unlist", "key", key, "owner", who.String())
}
// Withdraw pays the caller everything credited to them and returns it.
//
// This is the only way coins leave the realm. The credit is zeroed before the
// transfer, so a reentrant call finds nothing left to take.
func Withdraw(cur realm) int64 {
who := caller(cur)
amount, err := list.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
}
// Get returns what is known about an entry: its URL, its description, its
// owner, the deposit behind it, the height it was listed at, and its state,
// which is one of "listed", "challenged" or "removed".
//
// A key that was never applied for reads as the zero value with an empty
// state, which is how a caller tells it from a removed one.
func Get(key string) (url, description string, owner address, deposit, at int64, state string) {
e, ok := list.Get(key)
if !ok {
return "", "", "", 0, 0, ""
}
return e.URL, e.Description, e.Owner, e.Deposit, e.At, e.State.String()
}
// Count is how many entries are on the list right now. A challenged entry
// counts: a challenge is an objection, not a verdict.
func Count() int { return list.Count() }
// Listed is every key on the list, oldest first.
func Listed() []string {
entries := list.Listed()
out := make([]string, 0, len(entries))
for _, e := range entries {
out = append(out, e.Key)
}
return out
}
// IsListed reports whether key is on the list right now.
func IsListed(key string) bool { return list.IsListed(key) }
// ChallengeOf returns the open challenge against key: who opened it, the bond
// they put up, the height voting closes at, the two vote counts, and whether
// there is one at all.
func ChallengeOf(key string) (challenger address, bond, deadline, keep, remove int64, open bool) {
c, ok := list.ChallengeOf(key)
if !ok {
return "", 0, 0, 0, 0, false
}
return c.Challenger, c.Bond, c.Deadline, c.Keep, c.Remove, true
}
// CreditOf is what who can collect with [Withdraw] right now.
func CreditOf(who address) int64 { return list.CreditOf(who) }
// 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()
}
curated_test.gno
package curated
import (
"strings"
"testing"
"chain"
"chain/banker"
"chain/runtime"
cu "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/curated/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
var realmAddr = chain.PackageAddress(realmPath)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
dave = testutils.TestAddress("dave")
)
// reset clears realm state. Realm globals live for the whole test binary, so
// every entry, challenge and credit a later test reads starts here. The BANK
// does not carry over the same way, which is why every balance is asserted in
// the test that issued it.
func reset() {
list = cu.New(Deposit, ChallengeBlocks)
}
// pay credits the realm the way a real transaction would: the runtime deposits
// the envelope at the realm's address, then OriginSend reports it to the
// crossing function.
func pay(amount int64) {
testing.IssueCoins(realmAddr, chain.Coins{{Denom, amount}})
testing.SetOriginSend(chain.Coins{{Denom, amount}})
}
// apply lists an entry as who. It crosses immediately after SetRealm, which is
// what makes the account switch take: a helper that sets the realm and does
// not itself cross is silently ignored.
func apply(cur realm, who address, key, url, description string) {
pay(Deposit)
testing.SetRealm(testing.NewUserRealm(who))
Apply(cross(cur), key, url, description)
}
// challenge objects to an entry as who, bonding what that entry's deposit was.
func challenge(cur realm, who address, key string) {
_, _, _, bond, _, _ := Get(key)
pay(bond)
testing.SetRealm(testing.NewUserRealm(who))
Challenge(cross(cur), key)
}
// balance is what addr holds on chain right now.
func balance(addr address) int64 {
return banker.NewReadonlyBanker().GetCoins(addr).AmountOf(Denom)
}
func TestApplyTakesExactlyTheDepositAndListsAtOnce(cur realm, t *testing.T) {
reset()
// Underpaying and overpaying are both refused: a realm that silently kept
// the excess would have invented a fee nobody agreed to.
pay(Deposit - 1)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "costs exactly", func() {
Apply(cross(cur), "gnoswap", "https://gnoswap.io", "an AMM")
})
pay(Deposit + 1)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "costs exactly", func() {
Apply(cross(cur), "gnoswap", "https://gnoswap.io", "an AMM")
})
uassert.Equal(t, 0, Count())
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM on gno.land")
url, description, owner, deposit, at, state := Get("gnoswap")
uassert.Equal(t, "https://gnoswap.io", url)
uassert.Equal(t, "an AMM on gno.land", description)
uassert.Equal(t, alice.String(), owner.String())
uassert.Equal(t, Deposit, deposit)
uassert.Equal(t, runtime.ChainHeight(), at)
uassert.Equal(t, "listed", state)
uassert.True(t, IsListed("gnoswap"))
uassert.Equal(t, 1, Count())
urequire.Equal(t, 1, len(Listed()))
uassert.Equal(t, "gnoswap", Listed()[0])
// A key that was never applied for reads as the empty state.
_, _, _, _, _, state = Get("nothing")
uassert.Equal(t, "", state)
uassert.False(t, IsListed("nothing"))
}
func TestApplyRefusesAKeyAlreadyOnTheList(cur realm, t *testing.T) {
reset()
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM")
pay(Deposit)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "already on the list", func() {
Apply(cross(cur), "gnoswap", "https://mine.io", "mine now")
})
pay(Deposit)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "not a key", func() {
Apply(cross(cur), "GnoSwap", "https://mine.io", "mine now")
})
uassert.Equal(t, 1, Count())
}
func TestChallengeMatchesTheDepositAndOpensAVote(cur realm, t *testing.T) {
reset()
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM")
// Not a bond, not an entry: the entry is checked before the money is.
pay(Deposit)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "is not an entry that can be challenged", func() {
Challenge(cross(cur), "nothing")
})
// An owner shielding their own entry would cost them nothing.
pay(Deposit)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "cannot challenge their own entry", func() {
Challenge(cross(cur), "gnoswap")
})
opened := runtime.ChainHeight()
challenge(cur, bob, "gnoswap")
challenger, bond, deadline, keep, remove, open := ChallengeOf("gnoswap")
urequire.True(t, open, "the challenge is readable")
uassert.Equal(t, bob.String(), challenger.String())
uassert.Equal(t, Deposit, bond)
uassert.Equal(t, opened+ChallengeBlocks, deadline)
uassert.Equal(t, int64(0), keep)
uassert.Equal(t, int64(0), remove)
uassert.True(t, IsListed("gnoswap"), "a challenge is an objection, not a verdict")
// One address, one vote, and only while the window is open.
testing.SetRealm(testing.NewUserRealm(carol))
Vote(cross(cur), "gnoswap", false)
testing.SetRealm(testing.NewUserRealm(carol))
uassert.AbortsContains(t, cur, "one address, one vote", func() {
Vote(cross(cur), "gnoswap", true)
})
testing.SkipHeights(ChallengeBlocks)
testing.SetRealm(testing.NewUserRealm(dave))
uassert.AbortsContains(t, cur, "deadline has passed", func() {
Vote(cross(cur), "gnoswap", true)
})
}
// The full round, with the coins checked against the chain rather than against
// the realm's own books.
func TestResolveRemovesAnEntryAndPaysTheChallenger(cur realm, t *testing.T) {
reset()
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM")
challenge(cur, bob, "gnoswap")
uassert.Equal(t, 2*Deposit, balance(realmAddr), "both stakes are at the realm")
testing.SetRealm(testing.NewUserRealm(carol))
Vote(cross(cur), "gnoswap", false)
testing.SetRealm(testing.NewUserRealm(dave))
Vote(cross(cur), "gnoswap", false)
testing.SetRealm(testing.NewUserRealm(carol))
uassert.AbortsContains(t, cur, "still open", func() { Resolve(cross(cur), "gnoswap") })
testing.SkipHeights(ChallengeBlocks)
// Anyone may settle it, including somebody with nothing on the outcome.
testing.SetRealm(testing.NewUserRealm(carol))
Resolve(cross(cur), "gnoswap")
uassert.False(t, IsListed("gnoswap"))
uassert.Equal(t, 0, Count())
uassert.Equal(t, 2*Deposit, CreditOf(bob), "the bond back, plus alice's deposit")
uassert.Equal(t, int64(0), CreditOf(alice))
uassert.Equal(t, int64(0), CreditOf(carol), "voters are paid nothing in v0")
uassert.Equal(t, 2*Deposit, balance(realmAddr), "credited is not sent")
before := balance(bob)
testing.SetRealm(testing.NewUserRealm(bob))
got := Withdraw(cross(cur))
uassert.Equal(t, 2*Deposit, got)
uassert.Equal(t, before+2*Deposit, balance(bob), "the coins actually arrived")
uassert.Equal(t, int64(0), balance(realmAddr), "and the realm kept nothing")
// A second call, which is what a reentrant one would be, finds nothing.
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "nothing to withdraw", func() { Withdraw(cross(cur)) })
}
func TestATieKeepsTheEntryAndPaysTheOwner(cur realm, t *testing.T) {
reset()
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM")
challenge(cur, bob, "gnoswap")
testing.SetRealm(testing.NewUserRealm(carol))
Vote(cross(cur), "gnoswap", true)
testing.SetRealm(testing.NewUserRealm(dave))
Vote(cross(cur), "gnoswap", false)
testing.SkipHeights(ChallengeBlocks)
testing.SetRealm(testing.NewUserRealm(bob))
Resolve(cross(cur), "gnoswap")
uassert.True(t, IsListed("gnoswap"), "the incumbent wins ties")
uassert.Equal(t, Deposit, CreditOf(alice), "and takes the challenger's bond")
uassert.Equal(t, int64(0), CreditOf(bob))
// Her own deposit is still locked behind the entry, so only the bond is
// collectable until she unlists.
before := balance(alice)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.Equal(t, Deposit, Withdraw(cross(cur)))
uassert.Equal(t, before+Deposit, balance(alice))
uassert.Equal(t, Deposit, balance(realmAddr), "the deposit stays behind the entry")
}
// Nobody voting is a tie too, which is the common case and the one that
// decides whether a challenge is cheap. It is not: it costs the bond.
func TestAChallengeNobodyVotedOnLoses(cur realm, t *testing.T) {
reset()
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM")
challenge(cur, bob, "gnoswap")
testing.SkipHeights(ChallengeBlocks)
testing.SetRealm(testing.NewUserRealm(bob))
Resolve(cross(cur), "gnoswap")
uassert.True(t, IsListed("gnoswap"))
uassert.Equal(t, Deposit, CreditOf(alice))
uassert.Equal(t, int64(0), CreditOf(bob), "being wrong costs the bond")
}
func TestUnlistIsTheOwnersAndNotWhileChallenged(cur realm, t *testing.T) {
reset()
apply(cur, alice, "gnoswap", "https://gnoswap.io", "an AMM")
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "only the entry's owner", func() {
Unlist(cross(cur), "gnoswap")
})
challenge(cur, bob, "gnoswap")
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "under challenge", func() {
Unlist(cross(cur), "gnoswap")
})
uassert.Equal(t, int64(0), CreditOf(alice), "she cannot walk away mid-challenge")
testing.SkipHeights(ChallengeBlocks)
testing.SetRealm(testing.NewUserRealm(alice))
Resolve(cross(cur), "gnoswap")
testing.SetRealm(testing.NewUserRealm(alice))
Unlist(cross(cur), "gnoswap")
uassert.False(t, IsListed("gnoswap"))
uassert.Equal(t, 2*Deposit, CreditOf(alice), "the bond she won, and her deposit back")
// The key is free again, and re-listing it costs a fresh deposit.
apply(cur, bob, "gnoswap", "https://mine.io", "mine now")
_, _, owner, _, _, state := Get("gnoswap")
uassert.Equal(t, bob.String(), owner.String())
uassert.Equal(t, "listed", state)
}
// The realm holds exactly what it is accountable for, at every step: a stake
// behind something live, or a credit somebody has not collected yet.
func TestTheRealmHoldsExactlyWhatItOwes(cur realm, t *testing.T) {
reset()
check := func(step string) {
t.Helper()
uassert.Equal(t, list.Locked()+list.Owed(), balance(realmAddr), step)
}
check("empty")
apply(cur, alice, "one", "https://1.io", "first")
check("after a listing")
apply(cur, bob, "two", "https://2.io", "second")
check("after a second listing")
challenge(cur, bob, "one")
check("after a challenge")
testing.SetRealm(testing.NewUserRealm(carol))
Vote(cross(cur), "one", false)
check("after a vote")
testing.SkipHeights(ChallengeBlocks)
testing.SetRealm(testing.NewUserRealm(carol))
Resolve(cross(cur), "one")
check("after a resolution")
testing.SetRealm(testing.NewUserRealm(bob))
Withdraw(cross(cur))
check("after the winner collected")
testing.SetRealm(testing.NewUserRealm(bob))
Unlist(cross(cur), "two")
check("after an unlisting")
testing.SetRealm(testing.NewUserRealm(bob))
Withdraw(cross(cur))
check("after the deposit came back")
uassert.Equal(t, int64(0), balance(realmAddr), "and the realm is empty again")
}
// A URL is caller-supplied too, and it is the one string that reaches the
// renderer as a link target rather than as text.
func TestAPipeInAUrlCannotOpenAColumn(cur realm, t *testing.T) {
reset()
apply(cur, alice, "weird", "https://x.io/a|b", "a url with a pipe in it")
index := Render("")
uassert.False(t, strings.Contains(index, "https://x.io/a|b"),
"the raw pipe would open a column: "+index)
uassert.True(t, strings.Contains(index, "https://x.io/a%7Cb"),
"the link sanitizer percent-encodes it: "+index)
}
// 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()
apply(cur, alice, "gnoswap", "https://gnoswap.io/pools?a=1", "an AMM | with [a link](x)")
index := Render("")
uassert.True(t, strings.Contains(index, "# Curated"), index)
uassert.True(t, strings.Contains(index, "| 1 | 0 |"), "one listed, none challenged: "+index)
uassert.True(t, strings.Contains(index, "func=Apply"), "the index offers the transaction")
uassert.True(t, strings.Contains(index, "Voters are paid nothing"), "the index says what v0 does not do")
uassert.True(t, strings.Contains(index, "an AMM \\| with \\[a link\\]\\(x\\)"),
"a pipe in a description cannot open a column, and its markdown is inert: "+index)
entry := Render("entry/gnoswap")
uassert.True(t, strings.Contains(entry, "# gnoswap"), entry)
uassert.True(t, strings.Contains(entry, "an AMM | with \\[a link\\]\\(x\\)"),
"the description is escaped in prose too, where a pipe is not special: "+entry)
uassert.True(t, strings.Contains(entry, "func=Challenge"))
uassert.True(t, strings.Contains(entry, "func=Unlist"))
// Under challenge the page offers the two votes instead.
challenge(cur, bob, "gnoswap")
entry = Render("entry/gnoswap")
uassert.True(t, strings.Contains(entry, "## Under challenge"), entry)
uassert.True(t, strings.Contains(entry, "keep=true"), entry)
uassert.True(t, strings.Contains(entry, "keep=false"), entry)
uassert.False(t, strings.Contains(entry, "func=Unlist"), "an owner cannot walk away here either")
uassert.True(t, strings.Contains(Render(""), "## Open challenges"))
testing.SetRealm(testing.NewUserRealm(carol))
Vote(cross(cur), "gnoswap", false)
testing.SetRealm(testing.NewUserRealm(dave))
Vote(cross(cur), "gnoswap", false)
// Past the deadline it offers the settlement instead of the votes.
testing.SkipHeights(ChallengeBlocks)
entry = Render("entry/gnoswap")
uassert.True(t, strings.Contains(entry, "func=Resolve"), entry)
uassert.False(t, strings.Contains(entry, "keep=true"), "voting is over: "+entry)
// Removed, the key is advertised as free again.
testing.SetRealm(testing.NewUserRealm(bob))
Resolve(cross(cur), "gnoswap")
entry = Render("entry/gnoswap")
uassert.True(t, strings.Contains(entry, "free to apply for again"), entry)
uassert.True(t, strings.Contains(Render(""), "Nothing is on the list yet."))
uassert.Equal(t, "# Curated\nNo entry named nope", Render("entry/nope"))
uassert.True(t, strings.HasPrefix(Render("elsewhere"), "# Not found"))
}
// A realm that forwards a user's call must not be able to spend the user's
// envelope as if it were its own. OriginSend reports what the SIGNER attached
// to the transaction, so without the IsUserCall guard a realm that received
// one GNOT could call in here repeatedly, each call reading the same send and
// listing another entry for free. That is r/moul/grant Fund, and gnovet's
// origin-send-unguarded rule caught this exact shape here in CI after the
// local gate had passed.
func TestOnlyAUserCanPayIn(cur realm, t *testing.T) {
reset()
pay(Deposit)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/g1relay/forwarder"))
uassert.AbortsContains(t, cur, "must be a direct user transaction", func() {
Apply(cross(cur), "relayed", "/r/x", "paid with somebody else's coins")
})
uassert.Equal(t, 0, Count(), "nothing was listed")
apply(cur, alice, "real", "/r/real", "a real entry")
pay(Deposit)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/g1relay/forwarder"))
uassert.AbortsContains(t, cur, "must be a direct user transaction", func() {
Challenge(cross(cur), "real")
})
_, _, _, _, _, open := ChallengeOf("real")
uassert.False(t, open, "no challenge was opened")
}
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/curated/v0" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914348 max_deposit = "17000000ugnot"
render.gno
package curated
import (
"strconv"
"strings"
"chain/runtime"
"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"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/txlink/v0"
cu "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/curated/v0"
)
// Render routes two views: the list itself, and one entry.
//
// A key never contains a slash, so "entry/<key>" is a prefix strip rather than
// a path element that would have to be rejoined.
func Render(path string) string {
req := realmpath.Parse(path)
switch {
case strings.HasPrefix(req.Path, "entry/"):
return renderEntry(strings.TrimPrefix(req.Path, "entry/"))
case req.Path == "":
return renderIndex()
default:
return md.H1("Not found") + "No such view: " + ui.Inline(req.Path)
}
}
func renderIndex() string {
out := md.H1("Curated")
out += "A list you pay to be on, and can be paid for getting somebody off. " +
"The deposit does not make an entry good: it makes a bad one expensive " +
"to leave standing, because anybody who disagrees can put the same " +
"amount at risk and take it.\n\n"
open := list.Challenged()
t := ui.NewTable("on the list", "open challenges", "deposit", "window", "locked", "credited")
t.Row(
strconv.Itoa(list.Count()),
strconv.Itoa(len(open)),
num.GNOTf(Deposit),
strconv.FormatInt(ChallengeBlocks, 10)+" blocks",
num.GNOTf(list.Locked()),
num.GNOTf(list.Owed()),
)
out += t.String()
out += md.H2("The list")
out += listing(list.Listed())
out += "\n" + md.Link("β Apply for "+num.GNOTf(Deposit), applyURL()) + "\n"
if len(open) > 0 {
out += md.H2("Open challenges")
out += challengeTable(open)
}
out += md.H2("How it works")
out += md.BulletList([]string{
"**Apply** locks " + num.GNOTf(Deposit) + " and lists the entry immediately. " +
"There is no application period in v0.",
"**Challenge** matches that entry's deposit with a bond and opens a vote " +
"for " + strconv.FormatInt(ChallengeBlocks, 10) + " blocks. An owner cannot challenge their own entry.",
"**Vote** is one address, one vote, unweighted. An address is free, so read " +
"a resolution as nobody with a stake objecting, never as a verdict.",
"**Resolve** can be called by anyone once the window closes. A majority to " +
"keep credits the owner the bond; otherwise the challenger takes the bond " +
"and the deposit. A tie keeps the entry, so a challenge that convinced " +
"nobody loses its bond.",
"**Voters are paid nothing** in v0, which is the first thing to fix: the only " +
"two addresses with a reason to vote are the ones with money on the outcome.",
"**Nothing is ever sent to you.** Every payout is a credit, and " +
md.InlineCode("Withdraw()") + " collects it.",
})
return out
}
func renderEntry(key string) string {
e, ok := list.Get(key)
if !ok {
return md.H1("Curated") + "No entry named " + ui.Inline(key)
}
out := md.H1(ui.Inline(e.Key))
out += md.Blockquote(ui.Inline(e.Description)) + "\n"
// ShortN truncates without escaping and md.Link escapes what it is given:
// ui.Inline here would escape twice and render the backslashes.
out += md.Link(ui.ShortN(e.URL, 60, 0), e.URL) + "\n\n"
t := ui.NewTable("owner", "deposit", "listed at", "state")
t.Row(
ui.Addr(e.Owner),
num.GNOTf(e.Deposit),
"block "+strconv.FormatInt(e.At, 10),
e.State.String(),
)
out += t.String()
c, challenged := list.ChallengeOf(e.Key)
switch {
case challenged:
out += md.H2("Under challenge")
out += challengeTable([]*cu.Entry{e})
if c.Open(runtime.ChainHeight()) {
out += "\n" + ui.Action("π Keep", "Vote", "key", e.Key, "keep", "true") +
" Β· " + ui.Action("π Remove", "Vote", "key", e.Key, "keep", "false") + "\n"
} else {
out += "\n" + ui.Action("βοΈ Resolve", "Resolve", "key", e.Key) +
" Β· the window has closed and anyone can settle it\n"
}
case e.Live():
out += "\n" + md.Link("π© Challenge for "+num.GNOTf(e.Deposit), challengeURL(e.Key, e.Deposit)) +
" Β· " + ui.Action("π Unlist", "Unlist", "key", e.Key) + "\n"
default:
out += "\n" + ui.Empty("Off the list. The key is free to apply for again.")
out += md.Link("β Apply for "+num.GNOTf(Deposit), applyURL()) + "\n"
}
return out
}
// listing renders the entries as the list itself: the key links to its page,
// the description links to the thing it describes.
func listing(entries []*cu.Entry) string {
if len(entries) == 0 {
return ui.Empty("Nothing is on the list yet.")
}
t := ui.NewTable("key", "what", "link", "owner", "since", "state")
for _, e := range entries {
mark := ""
if e.State == cu.StateChallenged {
mark = " π©"
}
t.Row(
// A key is charset-validated, so md.Link's escaping is the whole
// story for it. A description is not: md.Link escapes markdown
// but NOT the pipe, which in a cell would open a column, so the
// description is never a link title here. Cut first with ShortN,
// which does not escape, then escape once with ui.Cell.
md.Link(ui.ShortN(e.Key, 32, 0), entryURL(e.Key)),
ui.Cell(ui.ShortN(e.Description, 48, 0)),
md.Link("β", e.URL),
ui.Addr(e.Owner),
"block "+strconv.FormatInt(e.At, 10),
e.State.String()+mark,
)
}
return t.String()
}
// challengeTable renders the open challenge against each of entries. An entry
// with none is skipped rather than shown blank.
func challengeTable(entries []*cu.Entry) string {
t := ui.NewTable("entry", "challenger", "bond", "keep", "remove", "voting closes")
now := runtime.ChainHeight()
for _, e := range entries {
c, ok := list.ChallengeOf(e.Key)
if !ok {
continue
}
closes := "block " + strconv.FormatInt(c.Deadline, 10)
if !c.Open(now) {
closes = "closed, awaiting `Resolve`"
}
t.Row(
md.Link(ui.ShortN(e.Key, 32, 0), entryURL(e.Key)),
ui.Addr(c.Challenger),
num.GNOTf(c.Bond),
strconv.FormatInt(c.Keep, 10),
strconv.FormatInt(c.Remove, 10),
closes,
)
}
return t.OrEmpty("No challenge is open.")
}
// entryURL is the gnoweb path of one entry's page.
//
// 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 to hardcode.
func entryURL(key string) string {
path := realmPath
if i := strings.Index(path, "/"); i >= 0 {
path = path[i:]
}
return path + ":entry/" + key
}
// applyURL is the Apply form with the deposit already attached, so a reader
// never has to work out what -send should say.
func applyURL() string {
return txlink.NewLink("Apply").SetSend(send(Deposit)).URL()
}
// challengeURL is the same for Challenge, carrying that entry's own bond.
func challengeURL(key string, bond int64) string {
return txlink.NewLink("Challenge").AddArgs("key", key).SetSend(send(bond)).URL()
}
func send(amount int64) string { return strconv.FormatInt(amount, 10) + Denom }