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

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

Playground

gnomod.toml

module = "gno.land/r/nym-moultest123/x/daily/merkledrop/v1"
gno = "0.9"
private = true

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186411
  max_deposit = "14000000ugnot"

merkledrop.gno

// Package merkledrop is a Merkle-gated airdrop that actually moves GNOT.
//
// It is the successor to r/moul/x/daily/merkledrop/v0, which was generated by
// the daily pipeline and is deployed on mainnet. v0 works, but it is a
// demonstration rather than a drop, and its proof scheme is safe by accident.
// Everything below is what changed and why.
//
// # 1. The leaf scheme is domain separated
//
// v0 hashed leaves bare and combined nodes commutatively, the OpenZeppelin
// scheme: leaf = sha256(addr|amount), node = sha256(min||max). Without a
// leaf/inner tag an inner-node hash is also a valid leaf hash, so anyone who
// can present a 64-byte leaf preimage can prove membership of a leaf that was
// never committed.
//
// v0 is not exploitable, but only by arithmetic: an inner preimage is exactly
// 64 bytes, and a v0 leaf preimage is at most 40 (bech32 address) + 1 + 20
// (uint64 has at most 20 digits) = 61 bytes. 61 < 64, so no collision is
// reachable. Change the leaf encoding, widen the amount, use a different
// address form, and the forgery goes live with no visible diff at the call
// site. That is not a property to rely on.
//
// v1 uses gno.land/p/nym-moultest123/x/merkle/v0, which is the Tendermint scheme: leaves
// are tagged 0x00 and inner nodes 0x01, so the two preimage spaces cannot
// overlap at any length.
//
// # 2. Proofs are bound to a position
//
// v0's proof was a bare sibling list of any length, folded until it ran out.
// v1's proof carries its index and the total leaf count, and the verifier
// rebuilds the tree shape from them: a proof cannot be replayed at another
// index, and one of the wrong length is rejected rather than folded. The
// sibling count is capped at merkle.MaxDepth, so an untrusted caller cannot
// choose the length of the loop.
//
// # 3. The root is settable, and the drop can close
//
// v0's root is a `const`, so the drop can never be re-rooted, extended or
// ended. v1's owner sets the root, the leaf count and an optional closing
// height, and can sweep the remainder once it closes.
//
// # 4. It moves real coins
//
// v0 keeps a uint64 ledger and moves nothing; its README says so, but it sits
// on mainnet reading like an airdrop. v1 sends ugnot from the realm's own
// address through the banker, and refuses a claim it cannot pay rather than
// marking it claimed.
//
// # Who the claimer is
//
// The claimer is PreviousRealm().Address(), the immediate caller. Called
// directly by a user that is the user; called through another realm it is that
// REALM. This is not a hole, because the leaf binds the address and the proof
// must match the claimer, so an intermediary can only claim an allocation
// granted to the intermediary itself. It does mean a wrapper realm cannot
// claim on a user's behalf, which is deliberate.
//
// Built on gno.land/p/nym-moultest123/x/merkle/v0.
package merkledrop

import (
	"errors"
	"strconv"
	"strings"

	"chain"
	"chain/banker"
	"chain/runtime"
	"chain/runtime/unsafe"

	"gno.land/p/nym-moultest123/x/merkle/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ownable/v0"
)

// Denom is the only coin this drop pays in.
const Denom = "ugnot"

// leafPrefix is part of every leaf preimage, so a proof for one drop cannot be
// replayed against another realm that happens to use the same encoding.
const leafPrefix = "gno.land/r/nym-moultest123/x/daily/merkledrop/v1"

// Owner may set the drop and sweep it.
//
// Hardcoded rather than derived from the deployer at init: inside a plain
// `func Test(t *testing.T)` the gno test runner reports OriginCaller() as the
// EMPTY address, so an owner taken from it is the empty address in every test
// and whatever deployed on chain. That divergence is exactly where an
// authorization bug hides, so the address is written down instead.
const Owner = address("g1manfred47kzduec920z88wfr64ylksmdcedlf5")

var (
	// Ownable holds the address allowed to set the drop and sweep it.
	Ownable *ownable.Ownable

	root     []byte   // the committed allocation root; nil means no drop
	total    int      // leaf count the root commits to
	closesAt int64    // chain height after which claims are refused; 0 = never
	claimed  avl.Tree // padded index -> claimer address string
	paid     int64    // running total of ugnot sent

	// demo holds the allocations of the seeded example drop, so Render can
	// show working proofs. A real drop commits only a root and leaves this
	// empty: the whole point of a Merkle drop is not storing the allocations.
	demo []Allocation
)

// Allocation is one entry of a drop: who may claim, and how much.
type Allocation struct {
	Address address
	Amount  int64
}

var (
	ErrNoDrop     = errors.New("merkledrop: no drop is configured")
	ErrClosed     = errors.New("merkledrop: the drop has closed")
	ErrClaimed    = errors.New("merkledrop: already claimed")
	ErrBadProof   = errors.New("merkledrop: invalid proof")
	ErrUnfunded   = errors.New("merkledrop: the drop cannot cover this claim")
	ErrStillOpen  = errors.New("merkledrop: the drop has not closed yet")
	ErrBadRoot    = errors.New("merkledrop: root must be 32 bytes of hex")
	ErrBadTotal   = errors.New("merkledrop: total must be positive")
	ErrBadAmount  = errors.New("merkledrop: amount must be positive")
)

func init() {
	Ownable = ownable.NewWithAddress(Owner)
	seed()
}

// Leaf returns the exact preimage committed for one allocation. Reproduce it
// off chain to rebuild the tree; it is the whole interface between the drop
// and its generator.
//
//	leaf = "<pkgpath>|<index>|<address>|<amount>"
func Leaf(index int, addr address, amount int64) string {
	return leafPrefix + "|" + strconv.Itoa(index) + "|" + addr.String() + "|" + strconv.FormatInt(amount, 10)
}

// SetDrop commits a new allocation root. Owner only.
//
// totalLeaves is the number of allocations the root commits to; the verifier
// needs it to rebuild the tree shape, so a wrong value invalidates every
// proof rather than weakening any. closesAtHeight is the last height at which
// a claim is accepted, or 0 for a drop that never closes.
//
// Setting a new root abandons the previous claim ledger: a drop is a
// commitment, and replacing it starts a new one.
func SetDrop(cur realm, rootHex string, totalLeaves int, closesAtHeight int64) {
	Ownable.AssertOwnedBy(unsafe.PreviousRealm().Address())
	rb, err := parseRoot(rootHex)
	if err != nil {
		panic(err.Error())
	}
	if totalLeaves <= 0 {
		panic(ErrBadTotal.Error())
	}
	root, total, closesAt = rb, totalLeaves, closesAtHeight
	claimed, paid, demo = avl.Tree{}, 0, nil
	chain.Emit("DropSet",
		"root", rootHex,
		"total", strconv.Itoa(totalLeaves),
		"closesAt", strconv.FormatInt(closesAtHeight, 10),
	)
}

// Claim proves the caller is allocated amount at index and pays it out.
//
// proof is the comma-separated hex sibling list from the tree generator, leaf
// first. It panics on a closed drop, a double claim, a bad proof, or a drop
// that cannot cover the amount; nothing is marked claimed in any of those
// cases.
func Claim(cur realm, index int, amount int64, proof string) {
	if len(root) == 0 {
		panic(ErrNoDrop.Error())
	}
	if IsClosed() {
		panic(ErrClosed.Error())
	}
	if amount <= 0 {
		panic(ErrBadAmount.Error())
	}
	if HasClaimed(index) {
		panic(ErrClaimed.Error())
	}

	claimer := unsafe.PreviousRealm().Address()
	p, err := merkle.ParseProof(index, total, proof)
	if err != nil {
		panic(ErrBadProof.Error())
	}
	if !p.Verify(root, []byte(Leaf(index, claimer, amount))) {
		panic(ErrBadProof.Error())
	}

	// Check funds BEFORE recording the claim, so an underfunded drop does not
	// burn an allocation.
	if Balance() < amount {
		panic(ErrUnfunded.Error())
	}

	claimed.Set(indexKey(index), claimer.String())
	paid += amount

	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bnk.SendCoins(Address(), claimer, chain.NewCoins(chain.NewCoin(Denom, amount)))

	chain.Emit("Claimed",
		"index", strconv.Itoa(index),
		"account", claimer.String(),
		"amount", strconv.FormatInt(amount, 10),
	)
}

// Sweep returns whatever is left to the owner, once the drop has closed. Owner
// only. A drop with no closing height can never be swept, which is the point
// of setting one.
func Sweep(cur realm) {
	owner := Ownable.Owner()
	Ownable.AssertOwnedBy(unsafe.PreviousRealm().Address())
	if closesAt == 0 || !IsClosed() {
		panic(ErrStillOpen.Error())
	}
	left := Balance()
	if left <= 0 {
		return
	}
	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bnk.SendCoins(Address(), owner, chain.NewCoins(chain.NewCoin(Denom, left)))
	chain.Emit("Swept", "amount", strconv.FormatInt(left, 10))
}

// Address returns the realm's own address, which is where the drop is funded.
// Send ugnot here to fund it.
func Address() address { return chain.PackageAddress(leafPrefix) }

// Balance returns the ugnot the drop still holds.
func Balance() int64 {
	return banker.NewReadonlyBanker().GetCoins(Address()).AmountOf(Denom)
}

// Root returns the committed root, hex-encoded, or "" when no drop is set.
func Root() string {
	if len(root) == 0 {
		return ""
	}
	return hexOf(root)
}

// Total returns the number of allocations the root commits to.
func Total() int { return total }

// ClosesAt returns the last height a claim is accepted, or 0 for never.
func ClosesAt() int64 { return closesAt }

// IsClosed reports whether the drop is past its closing height.
func IsClosed() bool { return closesAt != 0 && runtime.ChainHeight() > closesAt }

// Paid returns the ugnot claimed so far.
func Paid() int64 { return paid }

// Claims returns the number of allocations claimed.
func Claims() int { return claimed.Size() }

// HasClaimed reports whether the allocation at index was claimed.
func HasClaimed(index int) bool { return claimed.Has(indexKey(index)) }

// ClaimedBy returns the address that claimed index, or the empty address.
func ClaimedBy(index int) address {
	v := claimed.Get(indexKey(index))
	if v == nil {
		return ""
	}
	return address(v.(string))
}

// Verify checks an allocation against the committed root without claiming it,
// so a recipient can confirm a proof before spending gas on Claim.
func Verify(index int, addr address, amount int64, proof string) bool {
	if len(root) == 0 {
		return false
	}
	p, err := merkle.ParseProof(index, total, proof)
	if err != nil {
		return false
	}
	return p.Verify(root, []byte(Leaf(index, addr, amount)))
}

func parseRoot(s string) ([]byte, error) {
	p, err := merkle.ParseProof(0, 1, strings.TrimSpace(s))
	if err != nil || len(p.Siblings) != 1 {
		return nil, ErrBadRoot
	}
	return p.Siblings[0], nil
}

func hexOf(b []byte) string {
	const digits = "0123456789abcdef"
	out := make([]byte, 0, len(b)*2)
	for _, c := range b {
		out = append(out, digits[c>>4], digits[c&0x0f])
	}
	return string(out)
}

// indexKey pads the index so avl iteration is numeric, not lexicographic.
// ufmt has no width flags, so the padding is by hand: unpadded keys sort
// "0","1","10","11","2" and Render would lose the order past nine entries.
func indexKey(i int) string {
	s := strconv.Itoa(i)
	for len(s) < 6 {
		s = "0" + s
	}
	return s
}

merkledrop_test.gno

package merkledrop

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"testing"

	"gno.land/p/nym-moultest123/x/merkle/v0"
	"gno.land/p/nt/urequire/v0"
)

const (
	alice   = address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5") // demo index 0, 100
	bob     = address("g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj") // demo index 1, 250
	mallory = address("g1sqmuwtsrgd6t8y2n8f6z5xkltmpmcd64sx3vgg")
)

func fund(n int64) {
	testing.IssueCoins(Address(), chain.NewCoins(chain.NewCoin(Denom, n)))
}

func balanceOf(a address) int64 {
	return banker.NewReadonlyBanker().GetCoins(a).AmountOf(Denom)
}

// Every seeded allocation must verify against the seeded root, and no other
// address or amount may.
func TestDemoDropVerifies(t *testing.T) {
	seed()
	if Total() != 4 || Root() == "" {
		t.Fatalf("seed left Total=%d Root=%q", Total(), Root())
	}
	for i, a := range demoAllocations {
		proof := DemoProof(i)
		if !Verify(i, a.Address, a.Amount, proof) {
			t.Errorf("allocation %d does not verify", i)
		}
		if Verify(i, mallory, a.Amount, proof) {
			t.Errorf("allocation %d verified for the wrong address", i)
		}
		if Verify(i, a.Address, a.Amount+1, proof) {
			t.Errorf("allocation %d verified for the wrong amount", i)
		}
		if i > 0 && Verify(i-1, a.Address, a.Amount, proof) {
			t.Errorf("allocation %d verified at the wrong index", i)
		}
	}
}

// The leaf is the whole interface to an off-chain generator, so pin it.
func TestLeafEncoding(t *testing.T) {
	got := Leaf(3, alice, 1234)
	want := "gno.land/r/nym-moultest123/x/daily/merkledrop/v1|3|g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5|1234"
	if got != want {
		t.Errorf("Leaf = %q, want %q", got, want)
	}
}

func TestClaimPays(cur realm, t *testing.T) {
	seed()
	fund(1000)
	before := balanceOf(alice)

	testing.SetRealm(testing.NewUserRealm(alice))
	Claim(cross(cur), 0, 100, DemoProof(0))

	if got := balanceOf(alice) - before; got != 100 {
		t.Errorf("alice received %d ugnot, want 100", got)
	}
	if !HasClaimed(0) {
		t.Error("index 0 not marked claimed")
	}
	if ClaimedBy(0) != alice {
		t.Errorf("ClaimedBy(0) = %s, want alice", ClaimedBy(0))
	}
	if Paid() != 100 || Claims() != 1 {
		t.Errorf("Paid=%d Claims=%d, want 100 and 1", Paid(), Claims())
	}
	if Balance() != 900 {
		t.Errorf("drop balance %d, want 900", Balance())
	}
}

func TestClaimRejects(cur realm, t *testing.T) {
	seed()
	fund(1000)

	testing.SetRealm(testing.NewUserRealm(alice))
	urequire.AbortsContains(t, cur, "invalid proof", func() {
		Claim(cross(cur), 0, 999, DemoProof(0)) // wrong amount
	})
	urequire.AbortsContains(t, cur, "invalid proof", func() {
		Claim(cross(cur), 1, 250, DemoProof(1)) // bob's allocation, alice calling
	})
	urequire.AbortsContains(t, cur, "invalid proof", func() {
		Claim(cross(cur), 0, 100, "deadbeef") // malformed proof
	})
	urequire.AbortsContains(t, cur, "amount must be positive", func() {
		Claim(cross(cur), 0, 0, DemoProof(0))
	})

	testing.SetRealm(testing.NewUserRealm(mallory))
	urequire.AbortsContains(t, cur, "invalid proof", func() {
		Claim(cross(cur), 0, 100, DemoProof(0)) // not in the tree at all
	})

	// Nothing above may have consumed an allocation.
	if Claims() != 0 || Paid() != 0 {
		t.Errorf("a rejected claim left state behind: Claims=%d Paid=%d", Claims(), Paid())
	}
}

func TestDoubleClaimRejected(cur realm, t *testing.T) {
	seed()
	fund(1000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Claim(cross(cur), 1, 250, DemoProof(1))
	urequire.AbortsContains(t, cur, "already claimed", func() {
		Claim(cross(cur), 1, 250, DemoProof(1))
	})
	if Claims() != 1 {
		t.Errorf("Claims = %d, want 1", Claims())
	}
}

// An underfunded drop must refuse rather than mark the allocation claimed and
// leave the recipient with nothing to re-claim.
func TestUnderfundedDropDoesNotBurnAnAllocation(cur realm, t *testing.T) {
	seed()
	fund(10) // less than alice's 100
	testing.SetRealm(testing.NewUserRealm(alice))
	urequire.AbortsContains(t, cur, "cannot cover", func() {
		Claim(cross(cur), 0, 100, DemoProof(0))
	})
	if HasClaimed(0) {
		t.Error("a refused claim still consumed the allocation")
	}
	fund(1000)
	Claim(cross(cur), 0, 100, DemoProof(0))
	if !HasClaimed(0) {
		t.Error("the claim did not go through once funded")
	}
}

func TestSetDropOwnerOnly(cur realm, t *testing.T) {
	seed()
	newRoot := merkle.New([][]byte{[]byte("only-leaf")}).RootHex()

	testing.SetRealm(testing.NewUserRealm(mallory))
	urequire.AbortsContains(t, cur, "not owner", func() {
		SetDrop(cross(cur), newRoot, 1, 0)
	})

	testing.SetRealm(testing.NewUserRealm(Ownable.Owner()))
	SetDrop(cross(cur), newRoot, 1, 0)
	if Root() != newRoot || Total() != 1 {
		t.Errorf("SetDrop left Root=%s Total=%d", Root(), Total())
	}
	if len(demo) != 0 {
		t.Error("a real drop must not keep the seeded allocation list")
	}
	if Claims() != 0 || Paid() != 0 {
		t.Error("SetDrop did not reset the claim ledger")
	}
}

func TestSetDropRejectsBadInput(cur realm, t *testing.T) {
	seed()
	testing.SetRealm(testing.NewUserRealm(Ownable.Owner()))
	good := merkle.New([][]byte{[]byte("x")}).RootHex()
	urequire.AbortsContains(t, cur, "32 bytes of hex", func() { SetDrop(cross(cur), "zz", 1, 0) })
	urequire.AbortsContains(t, cur, "32 bytes of hex", func() { SetDrop(cross(cur), "abcd", 1, 0) })
	urequire.AbortsContains(t, cur, "total must be positive", func() { SetDrop(cross(cur), good, 0, 0) })
}

func TestClosingAndSweep(cur realm, t *testing.T) {
	seed()
	fund(1000)
	owner := Ownable.Owner()
	testing.SetRealm(testing.NewUserRealm(owner))

	// A drop that never closes can never be swept: that is what setting a
	// closing height buys.
	urequire.AbortsContains(t, cur, "not closed yet", func() { Sweep(cross(cur)) })

	closeAt := runtime.ChainHeight() + 10
	root := merkle.New([][]byte{[]byte(Leaf(0, alice, 100))}).RootHex()
	SetDrop(cross(cur), root, 1, closeAt)
	if IsClosed() {
		t.Fatal("drop closed before its height")
	}
	urequire.AbortsContains(t, cur, "not closed yet", func() { Sweep(cross(cur)) })

	testing.SkipHeights(11)
	if !IsClosed() {
		t.Fatal("drop still open past its closing height")
	}
	testing.SetRealm(testing.NewUserRealm(alice))
	urequire.AbortsContains(t, cur, "has closed", func() {
		Claim(cross(cur), 0, 100, "")
	})

	ownerBefore := balanceOf(owner)
	testing.SetRealm(testing.NewUserRealm(owner))
	Sweep(cross(cur))
	if Balance() != 0 {
		t.Errorf("drop balance after sweep = %d, want 0", Balance())
	}
	if balanceOf(owner)-ownerBefore != 1000 {
		t.Errorf("owner received %d, want 1000", balanceOf(owner)-ownerBefore)
	}
	seed()
}

func TestIndexKeyPadsForOrdering(t *testing.T) {
	// ufmt has no width flags, so the padding is by hand. Unpadded keys sort
	// "0","1","10","11","2" and Render loses the order past nine entries.
	if indexKey(7) != "000007" || indexKey(123456) != "123456" {
		t.Errorf("indexKey(7)=%q indexKey(123456)=%q", indexKey(7), indexKey(123456))
	}
	if !(indexKey(2) < indexKey(10)) {
		t.Error("padded keys do not sort numerically")
	}
}

render.gno

package merkledrop

import (
	"strconv"
	"strings"

	"gno.land/p/nym-moultest123/x/merkle/v0"
	"gno.land/p/nt/avl/v0"
)

// demoAllocations is the example drop seeded at deploy, so the realm renders
// working proofs instead of an empty page. A real drop calls SetDrop with a
// root computed off chain and stores no allocations at all.
var demoAllocations = []Allocation{
	{Address: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5", Amount: 100},
	{Address: "g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj", Amount: 250},
	{Address: "g1manfred47kzduec920z88wfr64ylksmdcedlf5", Amount: 500},
	{Address: "g1sss9uxef4l6lwc0mxq8n5v0e4vqpml7c39cxq2", Amount: 750},
}

// seed installs the example drop. Also called by the example tests: realm
// globals persist for a whole test binary and examples run after every Test,
// so a pinned Render must start from a known state.
func seed() {
	demo = demoAllocations
	tree := demoTree()
	root = tree.Root()
	total = len(demo)
	closesAt = 0
	claimed, paid = avl.Tree{}, 0
}

func demoTree() *merkle.Tree {
	leaves := make([][]byte, len(demo))
	for i, a := range demo {
		leaves[i] = []byte(Leaf(i, a.Address, a.Amount))
	}
	return merkle.New(leaves)
}

// DemoProof returns the proof for one seeded allocation, so the drop can be
// exercised end to end without an off-chain generator. It is empty once a real
// drop replaces the seeded one.
func DemoProof(index int) string {
	if index < 0 || index >= len(demo) {
		return ""
	}
	p, err := demoTree().Proof(index)
	if err != nil {
		return ""
	}
	return p.Hex()
}

// Render serves the drop overview at "" and one allocation at "proof/<index>".
func Render(path string) string {
	path = strings.TrimSpace(path)
	if strings.HasPrefix(path, "proof/") {
		return renderProof(strings.TrimPrefix(path, "proof/"))
	}
	return renderIndex()
}

func renderIndex() string {
	var b strings.Builder
	b.WriteString("# MerkleDrop v1\n\n")
	b.WriteString("A Merkle root gates an airdrop that pays real ugnot. Successor to\n")
	b.WriteString("[v0](/r/nym-moultest123/x/daily/merkledrop/v0), which moved no coins and whose proof scheme was\n")
	b.WriteString("safe only by accident of encoding lengths.\n\n")

	b.WriteString("## Drop\n\n")
	b.WriteString("| Field | Value |\n|---|---|\n")
	if len(root) == 0 {
		b.WriteString("| Root | _none configured_ |\n")
	} else {
		b.WriteString("| Root | `" + Root() + "` |\n")
	}
	b.WriteString("| Allocations | " + strconv.Itoa(total) + " |\n")
	b.WriteString("| Closes at height | " + closesLabel() + " |\n")
	b.WriteString("| Claimed | " + strconv.Itoa(Claims()) + " |\n")
	b.WriteString("| Paid out | " + strconv.FormatInt(Paid(), 10) + " ugnot |\n")
	b.WriteString("| Funding address | `" + Address().String() + "` |\n\n")

	b.WriteString("## How it differs from v0\n\n")
	b.WriteString("1. **Domain separated leaves.** v0 hashed leaves bare and combined nodes\n")
	b.WriteString("   commutatively, so an inner-node hash was also a valid leaf hash. It was not\n")
	b.WriteString("   exploitable, but only because a v0 leaf preimage tops out at 61 bytes while an\n")
	b.WriteString("   inner preimage is always 64. v1 tags leaves `0x00` and inner nodes `0x01`.\n")
	b.WriteString("2. **Proofs bound to a position.** v0 folded a sibling list of any length. v1\n")
	b.WriteString("   carries index and total, rebuilds the tree shape, and caps the depth.\n")
	b.WriteString("3. **A settable root and a closing height.** v0's root was a `const`.\n")
	b.WriteString("4. **Real coins.** v0 kept a `uint64` ledger and moved nothing.\n\n")

	b.WriteString("## Leaf encoding\n\n")
	b.WriteString("Reproduce this off chain to rebuild the tree:\n\n")
	b.WriteString("```\n")
	b.WriteString("leaf = \"" + leafPrefix + "|<index>|<address>|<amount>\"\n")
	b.WriteString("tree = Tendermint simple tree, leaf 0x00, inner 0x01\n")
	b.WriteString("```\n\n")

	if len(demo) == 0 {
		b.WriteString("## Allocations\n\n")
		b.WriteString("A live drop commits only its root, so there is nothing to list here.\n")
		return b.String()
	}
	b.WriteString("## Example allocations\n\n")
	b.WriteString("Seeded at deploy so the drop can be exercised without a generator. A live drop\n")
	b.WriteString("commits only a root and stores none of this.\n\n")
	b.WriteString("| # | Address | Amount | Claimed |\n|---|---|---|---|\n")
	for i, a := range demo {
		b.WriteString("| [" + strconv.Itoa(i) + "](/r/nym-moultest123/x/daily/merkledrop/v1:proof/" + strconv.Itoa(i) + ") | `" +
			a.Address.String() + "` | " + strconv.FormatInt(a.Amount, 10) + " | " + yesNo(HasClaimed(i)) + " |\n")
	}
	return b.String()
}

func renderProof(raw string) string {
	i, err := strconv.Atoi(raw)
	if err != nil || i < 0 || i >= len(demo) {
		return "# MerkleDrop v1\n\nNo allocation `" + raw + "`.\n"
	}
	a := demo[i]
	var b strings.Builder
	b.WriteString("# MerkleDrop v1: allocation " + strconv.Itoa(i) + "\n\n")
	b.WriteString("| Field | Value |\n|---|---|\n")
	b.WriteString("| Index | " + strconv.Itoa(i) + " |\n")
	b.WriteString("| Total | " + strconv.Itoa(total) + " |\n")
	b.WriteString("| Address | `" + a.Address.String() + "` |\n")
	b.WriteString("| Amount | " + strconv.FormatInt(a.Amount, 10) + " ugnot |\n")
	b.WriteString("| Claimed | " + yesNo(HasClaimed(i)) + " |\n\n")
	b.WriteString("## Leaf\n\n")
	b.WriteString("```\n" + Leaf(i, a.Address, a.Amount) + "\n```\n\n")
	b.WriteString("## Proof\n\n")
	b.WriteString("```\n" + DemoProof(i) + "\n```\n\n")
	b.WriteString("Only `" + a.Address.String() + "` can spend it: the address is inside the leaf, so\n")
	b.WriteString("the proof verifies for no one else.\n")
	return b.String()
}

func closesLabel() string {
	if closesAt == 0 {
		return "never"
	}
	return strconv.FormatInt(closesAt, 10)
}

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

render_example_test.gno

package merkledrop

// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
	seed()
	print(Render(""))
	// Output:
	// # MerkleDrop v1
	//
	// A Merkle root gates an airdrop that pays real ugnot. Successor to
	// [v0](/r/nym-moultest123/x/daily/merkledrop/v0), which moved no coins and whose proof scheme was
	// safe only by accident of encoding lengths.
	//
	// ## Drop
	//
	// | Field | Value |
	// |---|---|
	// | Root | `6964baa99da23b9d8c76774c6f1122b250040e29c1d75823dda15c043dc65755` |
	// | Allocations | 4 |
	// | Closes at height | never |
	// | Claimed | 0 |
	// | Paid out | 0 ugnot |
	// | Funding address | `g1jvh5ukk07dvd57fxefcp5aa29xaydxmxs7myyp` |
	//
	// ## How it differs from v0
	//
	// 1. **Domain separated leaves.** v0 hashed leaves bare and combined nodes
	//    commutatively, so an inner-node hash was also a valid leaf hash. It was not
	//    exploitable, but only because a v0 leaf preimage tops out at 61 bytes while an
	//    inner preimage is always 64. v1 tags leaves `0x00` and inner nodes `0x01`.
	// 2. **Proofs bound to a position.** v0 folded a sibling list of any length. v1
	//    carries index and total, rebuilds the tree shape, and caps the depth.
	// 3. **A settable root and a closing height.** v0's root was a `const`.
	// 4. **Real coins.** v0 kept a `uint64` ledger and moved nothing.
	//
	// ## Leaf encoding
	//
	// Reproduce this off chain to rebuild the tree:
	//
	// ```
	// leaf = "gno.land/r/nym-moultest123/x/daily/merkledrop/v1|<index>|<address>|<amount>"
	// tree = Tendermint simple tree, leaf 0x00, inner 0x01
	// ```
	//
	// ## Example allocations
	//
	// Seeded at deploy so the drop can be exercised without a generator. A live drop
	// commits only a root and stores none of this.
	//
	// | # | Address | Amount | Claimed |
	// |---|---|---|---|
	// | [0](/r/nym-moultest123/x/daily/merkledrop/v1:proof/0) | `g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5` | 100 | no |
	// | [1](/r/nym-moultest123/x/daily/merkledrop/v1:proof/1) | `g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj` | 250 | no |
	// | [2](/r/nym-moultest123/x/daily/merkledrop/v1:proof/2) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` | 500 | no |
	// | [3](/r/nym-moultest123/x/daily/merkledrop/v1:proof/3) | `g1sss9uxef4l6lwc0mxq8n5v0e4vqpml7c39cxq2` | 750 | no |
}

// ExampleRenderProof pins one allocation page, including its live proof.
func ExampleRenderProof() {
	seed()
	print(Render("proof/2"))
	// Output:
	// # MerkleDrop v1: allocation 2
	//
	// | Field | Value |
	// |---|---|
	// | Index | 2 |
	// | Total | 4 |
	// | Address | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |
	// | Amount | 500 ugnot |
	// | Claimed | no |
	//
	// ## Leaf
	//
	// ```
	// gno.land/r/nym-moultest123/x/daily/merkledrop/v1|2|g1manfred47kzduec920z88wfr64ylksmdcedlf5|500
	// ```
	//
	// ## Proof
	//
	// ```
	// 337bb23c66f621db38e704fc2d64d27d5fa6308a333fd9d2d69c6ccd9390c056,b498260d909eee2a1b8a88524d5e4d08128aa7d8ca433468379db031976958e1
	// ```
	//
	// Only `g1manfred47kzduec920z88wfr64ylksmdcedlf5` can spend it: the address is inside the leaf, so
	// the proof verifies for no one else.
}

// ExampleRenderMissingProof pins the not-found page.
func ExampleRenderMissingProof() {
	seed()
	print(Render("proof/99"))
	// Output:
	// # MerkleDrop v1
	//
	// No allocation `99`.
}